const odd = i => !!(~~i & 1);
odd(13024151);
const odd = i => i % 2;
odd(13024151);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Bitwise | |
Modulo |
Test name | Executions per second |
---|---|
Bitwise | 748106304.0 Ops/sec |
Modulo | 771437376.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition:
The provided Benchmark Definition is a simple JavaScript function that checks if a number is odd using two different approaches:
const odd = i => !!(~~i & 1);
&
) to check if the least significant bit of the number is set (i.e., if the number is odd).~~
operator is a bitwise NOT operator, which converts a number to its unsigned integer representation.const odd = i => i % 2;
%
) to check if the remainder of dividing the number by 2 is non-zero (i.e., if the number is odd).Options Compared:
The two approaches are compared in terms of their execution speed, which is measured in executions per second.
Pros and Cons:
Library Usage:
There is no explicit library usage in these benchmark definitions. However, it's worth noting that some JavaScript engines or platforms may have built-in optimizations or features that affect the execution speed of these functions.
Special JS Features/Syntax:
~~
operator used in the bitwise approach is a non-standard feature (not part of ECMAScript) and should be avoided in production code.i % 2
for determining oddness is a common convention, but it's not as low-level as the bitwise approach.Other Alternatives:
If you're looking for alternative approaches to determine if a number is odd, here are a few more:
Math.fround()
function with a small value (e.g., 0.00001) and checking if the result is close to the original value.Keep in mind that these alternatives may have performance implications, especially on low-end hardware or JavaScript engines.
Benchmark Preparation Code:
The provided Benchmark Definition includes a script preparation code, which sets up the test environment and defines the odd
function. The HTML preparation code is empty, indicating that no additional setup is required for the benchmark.
In summary, MeasureThat.net provides a simple and easy-to-use platform for comparing the performance of different JavaScript functions for determining if a number is odd. By analyzing the provided Benchmark Definition, we can see how two approaches are compared, and discuss their pros and cons.