var num = Math.random() * 100;
Math.trunc(num);
Math.floor(num);
parseInt(num);
~~(num);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Trunc | |
Floor | |
ParseInt | |
Bitwise invert2 |
Test name | Executions per second |
---|---|
Trunc | 133906240.0 Ops/sec |
Floor | 131874392.0 Ops/sec |
ParseInt | 90776032.0 Ops/sec |
Bitwise invert2 | 141727376.0 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Overview
The benchmark compares the performance of four different mathematical operations:
Math.trunc()
)These operations are used to truncate or round a given number to the nearest integer.
Trunc (Math.trunc())
Math.trunc()
is a built-in JavaScript function that truncates a specified number to an integer, rounding down if necessary. It's often used for converting decimal numbers to integers.
Pros:
Cons:
Floor
The floor()
function returns the largest integer less than or equal to a given number. It's similar to Trunc, but instead of truncating up, it truncates down.
Pros:
Cons:
ParseInt
parseInt()
converts a string or number to an integer. It's more complex than the other two methods, as it needs to parse the input value first.
Pros:
Cons:
Bitwise invert (~)
The bitwise invert operation (~) performs a bit-level operation on the input number. It inverts all bits of the binary representation, effectively performing a two's complement calculation.
Pros:
Cons:
DevicePlatform, OperatingSystem, and Browser
These fields represent the browser, device platform, and operating system used during the benchmarking process. This information helps identify any potential biases or variations in performance.
Alternatives
If you need to perform integer arithmetic operations with JavaScript, consider using:
Number()
function: returns an integer from a numeric stringInteger
object (in Node.js): provides a way to perform integer arithmeticHowever, for simple cases like the ones tested here, basic mathematical operations like Trunc, Floor, and ParseInt are sufficient. For more complex or high-performance applications, consider using specialized libraries or engines.
Other Considerations
Keep in mind that this benchmark only tests specific operations and does not account for other factors that might affect performance, such as:
When working with numerical computations in JavaScript, consider these aspects to ensure optimal performance.