arr = new Array(100).fill(null).map((_, i) => new Array(100).fill(null).map((_, j) => i + "," + j));
objA = {};
objB = {};
objs = [objA, objB];
randomValues = new Array(10000).fill(null).map(() => [Math.floor(Math.random()*100), Math.floor(Math.random()*100), objs[Math.floor(Math.random()*2)]]);
function getValue(obj, a , b) {
if(obj === objA)
return arr[a][b];
else
return arr[b][a];
}
const [a, b] = randomValues[Math.floor(Math.random()*10000)];
arr[a][b];
const [a, b, obj] = randomValues[Math.floor(Math.random()*10000)];
getValue(obj, a, b);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Normal access | |
Conditional index-swapped access |
Test name | Executions per second |
---|---|
Normal access | 2431450.8 Ops/sec |
Conditional index-swapped access | 1713081.9 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Benchmark Definition
The benchmark tests two ways to access elements in a 2D array: directly (arr[a][b]
) and through a conditional function (getValue(obj, a, b)
). The getValue
function checks if the object being accessed is objA
or objB
and returns the corresponding value from the arr
array.
Options Compared
The benchmark compares two approaches:
[a][b]
to access the element directly in the 2D array (arr[a][b]
).getValue
function to access the element conditionally, where the function checks if the object being accessed is one of the two objects (objA
or objB
) and returns the corresponding value.Pros and Cons
Library
The getValue
function uses an anonymous function (a lambda function) to perform the conditional check. This function takes three arguments (obj
, a
, and b
) and returns the corresponding value from the arr
array based on the condition.
Special JS Feature/Syntax
There are no special JavaScript features or syntax used in this benchmark.
Other Considerations
When writing a benchmark, consider the following:
Alternatives
If you're interested in exploring alternative approaches, here are some options:
getValue
, you could precompute the values and store them in an array or object, eliminating the need for a function call.Keep in mind that the best approach will depend on the specifics of your application and the requirements of your project.