var number = Number('20px');
var unary = +'20px';
var parse = parseFloat('20px');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Number | |
Unary + | |
parseFloat |
Test name | Executions per second |
---|---|
Number | 16541091.0 Ops/sec |
Unary + | 1006190912.0 Ops/sec |
parseFloat | 11397603.0 Ops/sec |
Let's break down the benchmark and its test cases.
Benchmark Overview
The benchmark compares three ways of handling measurements with units in JavaScript: using the built-in Number
function, unary plus (+
) operator, and parseFloat
. The goal is to determine which method is faster.
Test Cases
There are three test cases:
Number
function to parse a string containing a measurement with units ("20px"). This function attempts to convert the string to a number, ignoring any unit suffix.+
) operator to parse a string containing a measurement with units ("20px"). This method explicitly treats the leading +
as part of the measurement value.parseFloat
to parse a string containing a measurement with units ("20px"). This function is similar to Number
, but it returns a floating-point number, allowing for decimal values.Comparison
The benchmark compares the execution time of each test case on different browsers (Chrome 112) running on various platforms and operating systems. The results indicate that:
+
) tends to be faster than both Number
and parseFloat
.Number
is slower than unary plus, but potentially faster than parseFloat
for certain use cases.parseFloat
can be slower due to its additional complexity and floating-point conversion.Pros and Cons of Each Approach
Number
and parseFloat
.+
as part of the measurement value.
Cons:Number
.Other Considerations
Number
is often inlined by the optimizer, making it faster than the other two options.parseFloat
depends on the specific requirements of your project.Alternatives
Other ways to handle measurements with units in JavaScript include: