var p = [1,2,4,8,16,32,64,128,256,512];
for (var n=0;n<10;n++) {
var s = (Math.floor(65*0.098)+65)*p[n];
};
for (var n=0;n<10;n++) {
var s = (Math.floor(65*0.098)+65)*Math.pow(2,n);
};
var p = [1,2,4,8,16,32,64,128,256,512];
for (var n=0;n<10;n++) {
var s = (Math.floor(65/10.24)+65)*p[n];
};
for (var n=0;n<10;n++) {
var s = (Math.floor(65/10.24)+65)*Math.pow(2,n);
};
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Outside | |
Inside | |
Outside with division | |
Inside with division |
Test name | Executions per second |
---|---|
Outside | 18566682.0 Ops/sec |
Inside | 11878778.0 Ops/sec |
Outside with division | 18621244.0 Ops/sec |
Inside with division | 11797327.0 Ops/sec |
Let's dive into the provided benchmark definitions and explain what's being tested, compared, and their pros and cons.
Benchmark Definition
The benchmark definition is a JSON object that provides metadata about the test case. It contains:
Name
: A human-readable name for the benchmark.Description
: A brief description of the test case.Script Preparation Code
and Html Preparation Code
: These fields are empty, indicating that no setup code is required before running the benchmark.Individual Test Cases
There are four test cases, each representing a different way to calculate powers of two:
var p = [1,2,4,8,16,32,64,128,256,512];
for (var n=0;n<10;n++) {
var s = (Math.floor(65*0.098)+65)*p[n];
};
In this test case, the power of two is calculated by multiplying the element at index n
in the array p
with a scaled value. The calculation is done outside the loop.
for (var n=0;n<10;n++) {
var s = (Math.floor(65*0.098)+65)*Math.pow(2,n);
};
In this test case, the power of two is calculated using the Math.pow
function inside a loop.
var p = [1,2,4,8,16,32,64,128,256,512];
for (var n=0;n<10;n++) {
var s = (Math.floor(65/10.24)+65)*p[n];
};
In this test case, the power of two is calculated by dividing a scaled value and multiplying it with an element in the array p
. The calculation is done outside the loop.
for (var n=0;n<10;n++) {
var s = (Math.floor(65/10.24)+65)*Math.pow(2,n);
};
In this test case, the power of two is calculated using Math.pow
and a scaled value inside a loop.
Comparison
The main difference between these test cases is where the calculation of powers of two is performed: outside the loop (test cases 1 and 3) or inside the loop (test cases 2 and 4).
Pros and Cons:
Library Usage
None of the test cases use any external libraries.
Special JS Features/Syntax
None of the test cases use any special JavaScript features or syntax (e.g., async/await, Promises).
Other Alternatives
Other approaches to calculate powers of two could include:
__builtin_ctz
(for integer logarithm) or pow
with high precision.These alternatives may offer better performance or efficiency, but they are not tested in this benchmark.