var x = Math.random() * 100000000;
var y;
y = x % 2;
y = x & 1;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
modulus | |
bitwise |
Test name | Executions per second |
---|---|
modulus | 4524197.5 Ops/sec |
bitwise | 6189084.5 Ops/sec |
Let's break down what's being tested in the provided benchmark.
What is being tested?
The test is designed to compare the performance of three different approaches to achieve the same result: calculating the remainder of an integer division operation:
Math.floor()
Math.trunc()
~~
(two's complement), >> 0
, and other techniques.Options being compared
The test is comparing the performance of these three approaches for two individual test cases:
y = x % 2;
y = x & 1;
In each test case, the script preparation code generates a random integer x
and then calculates the result using one of the three approaches.
Pros and Cons
Here's a brief analysis of each approach:
floor()
but can return negative values if necessary.floor()
, and may be faster in some cases.Math
functions.Other considerations
The test also measures the performance of Firefox 83 on Linux desktops. This means that any differences in performance between approaches may be due to platform-specific optimizations or browser-specific behavior.
Library and special JS features
None of the test cases use any external libraries, but they do rely on the following special JavaScript features:
Math.random()
: a built-in function for generating random numbers.%
, &
): built-in operators that perform integer division and bitwise operations, respectively.Alternatives
If you want to compare the performance of other approaches or test different scenarios, here are some alternatives to explore:
x & 0xFF
instead of x & 1
) to see if you can find faster alternatives.Math.abs()
or Number.isInteger()
, that might be relevant for this type of calculation.