const obj = {
__value: 0,
get value() {
return this.__value;
},
set value(v) {
this.__value = v;
}
};
function increase() {
obj.value = obj.value + 1;
}
while (obj.value < 1000) {
increase();
}
const obj = {
__value: 0,
getValue() {
return this.__value;
},
setValue(v) {
this.__value = v;
}
};
function increase() {
obj.setValue(obj.getValue() + 1);
}
while (obj.getValue() < 1000) {
increase();
}
const obj = new Proxy(
{ value: 0 },
{
get(obj, key) { return obj[key] },
set(obj, key, value) { obj[key] = value },
}
);
function increase() {
obj.value = obj.value + 1;
}
while (obj.value < 1000) {
increase();
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Get/Set | |
Function | |
Proxy |
Test name | Executions per second |
---|---|
Get/Set | 18360.9 Ops/sec |
Function | 1048986.8 Ops/sec |
Proxy | 6100.0 Ops/sec |
The provided benchmark tests the performance of three different approaches for incrementing a value in an object: property get/set, function, and Proxy.
Property Get/Set
In this approach, the value
property is defined with both getter and setter methods. The getter method returns the current value, while the setter method updates the value. In the test case, the increase
function increments the value by 1 in each iteration of the loop.
Pros:
Cons:
Function
In this approach, two separate functions are defined: getValue
and setValue
. The getValue
function returns the current value, while the setValue
function updates the value. In the test case, the increase
function calls setValue
with the result of getValue
plus 1.
Pros:
Cons:
Proxy
In this approach, a Proxy object is created with two handlers: get
and set
. The get
handler returns the current value, while the set
handler updates the value. In the test case, the increase
function increments the value by 1 in each iteration of the loop.
Pros:
Cons:
Library Used
In all test cases, the Proxy
function is used from the JavaScript standard library. The purpose of Proxy
is to create an object that can be manipulated by defining getters and setters on its properties.
Special JS Features/ Syntax
None.
Other Alternatives