var num = Math.trunc(Math.random()*10);
num % 2
num ^ 1
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Modulo | |
Bitwise |
Test name | Executions per second |
---|---|
Modulo | 17981154.0 Ops/sec |
Bitwise | 19121954.0 Ops/sec |
Let's break down the provided benchmark configuration and explanation.
Benchmark Overview
The provided benchmark measures the performance of two different approaches to check if a number is even: using the modulo operator (%
) and bitwise operations (^
). The benchmark is run in Chrome 120 on a Windows desktop.
Script Preparation Code
The script preparation code initializes a variable num
with a random integer value between 0 and 9, generated using Math.trunc(Math.random()*10)
.
Html Preparation Code
There is no HTML preparation code provided, which means that the benchmark only runs in a Node.js environment (since MeasureThat.net is a Node.js-based tool).
Benchmark Definition JSON
The benchmark definition consists of two individual test cases:
%
) to check if num
is even. The Benchmark Definition
string is simply "num % 2", which means that the code will calculate the remainder of num
divided by 2.^
) to check if num
is odd. The Benchmark Definition
string is "num ^ 1", which means that the code will perform a bitwise XOR operation between num
and 1.Libraries
There are no libraries used in this benchmark, so there's nothing to discuss.
Special JS Features/Syntax
The benchmark uses two special JavaScript features:
^
operator is used for bitwise XOR, which performs a binary operation on the bits of its operands.Math.random()
function generates a random number between 0 (inclusive) and 1 (exclusive).Pros and Cons
Here's a brief summary of the pros and cons of each approach:
%
):^
):Other Alternatives
If you want to measure the performance of other approaches to check if a number is even, here are some alternatives:
&
operator with the bitwise AND mask 1 (num & 1 == 0
) for an even simpler implementation.if (num % 2 === 0) { ... }
) which may be more intuitive but potentially slower.Keep in mind that these alternatives might not provide the same level of optimization as the bitwise XOR approach, and it's essential to profile and test your specific use cases before deciding on an implementation.