const obj = {a: 1, b: 2, c: 3, d: 4};
const sealedObj = Object.freeze({a: 1, b: 2, c: 3, d: 4, __proto__: null});
let v = null;
v = sealedObj.a;
v = sealedObj.b;
v = sealedObj.c;
v = sealedObj.d;
v = obj.a;
v = obj.b;
v = obj.c;
v = obj.d;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Frozen object access | |
Ordinary object access |
Test name | Executions per second |
---|---|
Frozen object access | 3080224.8 Ops/sec |
Ordinary object access | 3347081.2 Ops/sec |
The benchmark test conducted compares the performance of accessing properties in JavaScript between a regular (ordinary) object and a frozen object. Here’s a breakdown of the benchmark, its key elements, and underlying concepts:
Frozen Object Access: This test measures how quickly properties can be accessed in an object that has been frozen using Object.freeze()
.
Ordinary Object Access: This test measures the same property accesses but uses a regular JavaScript object that is not frozen.
Frozen Object (sealedObj
):
Object.freeze()
, which makes the object immutable. This means that once defined, properties cannot be added, removed, or modified. It also prevents changes to the prototype.Ordinary Object (obj
):
sealedObj
)Pros:
Cons:
obj
)Pros:
Cons:
The benchmark does not incorporate any external libraries; it relies on built-in JavaScript features such as Object.freeze()
, which is part of JavaScript's Object API. This method is designed specifically for making objects immutable, and it helps developers enforce state management within their applications.
Real-World Usage: The benefits of frozen objects are most apparent in applications where data integrity is crucial, such as Flux/Redux state management patterns or in functional programming.
Alternatives: Other alternatives for accessing properties in JavaScript include:
According to the latest results:
This shows that accessing properties from ordinary objects is faster than from frozen objects in this specific benchmark scenario, though the difference in performance generally varies based on the specific conditions and JavaScript engine optimizations present.