<!--your preparation HTML code goes here-->
const obj = { a: 1 };
const company1 = {
get ab() {
return (key) => {
return obj[key];
}
}
}
const api1 = {
get ab() {
return company1.ab;
}
}
const company2 = {
ab(key) {
return obj[key];
}
}
const api2 = {
ab: company2.ab,
}
api1.ab('a')
api2.ab('a')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
old | |
new |
Test name | Executions per second |
---|---|
old | 37218708.0 Ops/sec |
new | 150184672.0 Ops/sec |
The benchmark you're looking at compares two different approaches to accessing a value in a JavaScript object: the first method uses a getter with a closure, and the second uses a direct method call.
Using a Getter with Closure (Old Approach):
const company1 = {
get ab() {
return (key) => {
return obj[key];
}
}
};
const api1 = {
get ab() {
return company1.ab;
}
};
ab
, on company1
. When accessed, it returns a function that takes a key and retrieves a value from obj
. The getter in api1
simply returns the ab
from company1
.Using a Regular Function (New Approach):
const company2 = {
ab(key) {
return obj[key];
}
};
const api2 = {
ab: company2.ab,
};
ab
, directly on company2
which takes a key and returns the corresponding value from obj
.api2.ab('a')
) has a significantly higher execution speed, with 149,022,752 executions per second compared to 38,068,040 executions per second for the old approach. This suggests that using a direct method call is more efficient than using a getter that returns a closure.Getter with Closure (Old Approach):
Regular Function (New Approach):
Use Case Sensitivity: The choice between using getters or regular functions can depend on specific use cases. If you want to maintain state or encapsulate behavior, getters with closures can be beneficial. However, for performance-critical applications or scenarios where you simply need to access data, regular functions are preferable.
Memory Consumption: The closure approach could lead to higher memory consumption because every time the getter is called, a new function is created. This could be a concern in environments where performance and memory efficiency are critical.
In conclusion, when deciding between these approaches, consider the specific needs of your application: readability, maintainability, and performance. For straightforward data access, a direct method (like in the new approach) is usually the best choice.