var arr = new Array(10000).fill(0).map(() => Math.random() * 10);
arr.map(n => n >> 1);
arr.map(n => Math.floor(n / 2));
arr.map(n => ~~(n / 2));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Right shift | |
Divide and floor | |
Divide and floor 2 |
Test name | Executions per second |
---|---|
Right shift | 14431.3 Ops/sec |
Divide and floor | 644.0 Ops/sec |
Divide and floor 2 | 11045.2 Ops/sec |
Overview
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks. The benchmark provided measures the performance of three different approaches to divide an array by 2: right shift, divide and floor, and another variant of divide and floor using bitwise truncation (~~
).
Benchmark Definition JSON
The benchmark definition JSON contains information about the test case:
Name
: The name of the benchmark, which is "Right shift VS Divide and floor 2".Description
: An empty string, indicating that no description is provided.Script Preparation Code
: A script that generates an array of 10,000 random numbers between 0 and 10. This code is executed before each test case to ensure a fresh starting point for the tests.Html Preparation Code
: An empty string, indicating that no HTML preparation code is required.Individual Test Cases
The benchmark definition also contains three individual test cases:
>>
) on the generated array./
operator and then taking the floor value using Math.floor()
.~~
) to truncate the result to the nearest integer.Options Compared
The benchmark compares three different approaches:
>>
) to divide an array element by 2. This is a simple and efficient operation that relies on the binary representation of the numbers./
operator to divide an array element by 2, followed by Math.floor()
to take the floor value. This approach can be slower than right shift due to the overhead of the division operation.~~
) to truncate the result of dividing an array element by 2 to the nearest integer. This approach is similar to divide and floor but avoids the overhead of Math.floor()
.Pros and Cons
Here's a summary of the pros and cons of each approach:
/
operator followed by Math.floor()
.
Cons:Math.floor()
.Library: Math
The benchmark uses the Math
library for the Math.floor()
function, which is a standard JavaScript library that provides mathematical functions.
Special JS Feature/Syntax
None of the test cases use any special JavaScript features or syntax that are unique to modern browsers. They rely on basic JavaScript operations and libraries like Math
.
Other Alternatives
If you want to explore alternative approaches, here are some options:
/
operator without Math.floor()
.Keep in mind that the specific benchmark and test cases may not be representative of real-world scenarios, but they can still provide valuable insights into the performance characteristics of different JavaScript approaches.