var len = 10000000
var nums = Array(len)
.fill()
.map(() => Math.random() * 10000)
for (let i = 0; i < len; i++) {
const result = Math.floor(nums[i])
}
for (let i = 0; i < len; i++) {
const result = nums[i] | 0
}
for (let i = 0; i < len; i++) {
const result = parseInt(nums[i])
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Math.floor(N) | |
(N | 0) | |
parseInt(N) |
Test name | Executions per second |
---|---|
Math.floor(N) | 0.9 Ops/sec |
(N | 0) | 1.7 Ops/sec |
parseInt(N) | 0.9 Ops/sec |
Overview of the Benchmark
The provided benchmark measures the performance differences between three approaches to truncate negative numbers in JavaScript:
Math.floor(N)
: Uses the built-in floor
function from the Math object.(N | 0)
: Uses a bitwise OR operation with zero (|
is the bitwise OR operator).parseInt(N)
: Uses the parseInt
function to convert the number to an integer.Description of Each Approach
Math.floor(N)
floor
function from the Math object, which returns the largest integer less than or equal to the input value.(N | 0)
|
is the bitwise OR operator). In two's complement representation, subtracting zero from a negative number results in a positive value with the same bit pattern as the original negative number.Math.floor
or parseInt
.parseInt(N)
parseInt
function to convert the number to an integer.Library Used
None. The benchmark only uses built-in JavaScript functions and operators.
Special JS Feature/Syntax
None mentioned in the provided information.
Alternatives
If the goal is to measure the performance of integer truncation operations, alternative approaches could include:
big-integer
or decimal.js
for arbitrary-precision arithmetic.However, the benchmark as provided seems to be focused on measuring the performance differences between three standard JavaScript approaches, and alternative approaches would require additional setup and configuration.