class ValueHolder {
#value;
get value() {return this.#value;}
set value(v) {this.#value = v;}
}
const holder = new ValueHolder();
function getValue1(x) {
return holder.value;
}
function getValue2(x, anyHolder=holder) {
return anyHolder.value;
}
function getValue3(x, anyHolder=holder) {
const propName = "value";
return anyHolder[propName];
}
function getValue4(x, anyHolder=holder, propName="value") {
return anyHolder[propName];
}
function benchmark(func) {
let x;
for (let i = 0; i < 1000000; i++) {
x = func(i);
}
return x;
}
benchmark(getValue1)
benchmark(getValue2)
benchmark(getValue3)
benchmark(getValue4)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Static object, static property | |
Dynamic object, static property | |
Dynamic object, const property | |
Dynamic object, dynamic property |
Test name | Executions per second |
---|---|
Static object, static property | 3194.0 Ops/sec |
Dynamic object, static property | 343.3 Ops/sec |
Dynamic object, const property | 343.5 Ops/sec |
Dynamic object, dynamic property | 317.2 Ops/sec |
Let's break down the provided benchmark definition and test cases.
Benchmark Definition
The benchmark is designed to measure the speed of accessing class fields (properties) in JavaScript. The script preparation code defines a ValueHolder
class with a private field #value
. Three functions are created:
getValue1(x)
returns the value of the static property holder.value
.getValue2(x, anyHolder=holder)
returns the value of the dynamic object's static property using the anyHolder
parameter.getValue3(x, anyHolder=holder)
returns the value of a const property using the propName
variable.getValue4(x, anyHolder=holder, propName="value")
returns the value of a dynamic property using the propName
parameter.The benchmark function takes one argument, func
, which is expected to be one of these four functions. The benchmark measures how many executions per second are performed by each function over 1 million iterations.
Test Cases
There are four test cases, each corresponding to a different access pattern:
holder.value
using getValue1
.getValue2
.getValue3
.getValue4
.Options Compared
The benchmark compares four different access patterns:
holder.value
(Test Case 1).Pros and Cons of Each Approach
Library and Special Features
No specific libraries are mentioned, but the #value
syntax is a shorthand for private fields in modern JavaScript (ECMAScript 2020+). The use of const variables (const propName = "value";
) is also a good practice to ensure property accessibility is controlled.
Alternatives
Other alternatives could be considered, such as:
this
keyword to access properties directly on the object.Keep in mind that these alternatives would depend on the specific requirements and constraints of the project.
Please let me know if you'd like further clarification or details on any aspect!