var obj = { a:1 }
function setNumber(key, value) {
obj[key] = value;
}
function setCall(key, getValue) {
obj[key] = getValue(obj);
}
function setTypecheck(key, value) {
obj[key] = typeof value === "number" ? value : value(obj);
}
function getValue() {
return 100;
}
setNumber("a", 100);
setCall("a", getValue);
setTypecheck("a", 100);
setTypecheck("a", getValue);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
setNumber | |
setCall | |
setTypecheck(num) | |
setTypecheck(call) |
Test name | Executions per second |
---|---|
setNumber | 13312209.0 Ops/sec |
setCall | 6746080.5 Ops/sec |
setTypecheck(num) | 13313842.0 Ops/sec |
setTypecheck(call) | 6710818.5 Ops/sec |
I'll break down the provided benchmark JSON and explain what's being tested, compared, and their pros and cons.
Benchmark Definition:
The benchmark definition is a JSON object that describes the experiment:
{
"Name": "set num vs set fnCall vs typecheck then set",
"Description": null,
"Script Preparation Code": ...,
"Html Preparation Code": null
}
This benchmark involves three different approaches to set values on an object obj
:
obj[key] = value;
)obj[key] = getValue(obj);
)typeof value === "number"
, and then sets the value accordingly (obj[key] = typeof value === "number" ? value : value(obj);
)Individual Test Cases:
The benchmark consists of four test cases, each with its own Benchmark Definition
string:
[
{
"Benchmark Definition": "setNumber(\"a\", 100);",
"Test Name": "setNumber"
},
{
"Benchmark Definition": "setCall(\"a\", getValue);",
"Test Name": "setCall"
},
{
"Benchmark Definition": "setTypecheck(\"a\", 100);",
"Test Name": "setTypecheck(num)"
},
{
"Benchmark Definition": "setTypecheck(\"a\", getValue);",
"Test Name": "setTypecheck(call)"
}
]
Each test case measures the execution time of its corresponding benchmark definition.
Library:
The getValue
function is a custom library, not part of the standard JavaScript. Its purpose is to return a constant value (return 100;
) for use in the setCall
and setTypecheck
functions.
Special JS Feature/Syntax:
There are no special features or syntax mentioned in this benchmark.
Pros and Cons of Different Approaches:
Other Alternatives:
If not using getValue
, alternative implementations for the setCall
function could use other constant values or functions to simulate different scenarios.
For example, instead of getValue() { return 100; }
, you could use:
function setConstantValue(key, value) {
obj[key] = value;
}
This would remove the overhead of a function call and directly assign the value.