var testString = "123.456 unit"
var value = testString.split(" ")[0];
var result = "Final result: " + value;
var value = Number.parseFloat(testString);
var result = "Final result: " + value;
var value = testString.match(/[-\d.]*/);
var result = "Final result: " + value;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Splitting | |
parseFloat | |
regex |
Test name | Executions per second |
---|---|
Splitting | 47943160.0 Ops/sec |
parseFloat | 36350968.0 Ops/sec |
regex | 9730914.0 Ops/sec |
I'd be happy to explain the JavaScript microbenchmark on MeasureThat.net.
Benchmark Overview
The benchmark measures the performance of three different approaches to extract a number from a string: splitting, using parseFloat
, and using regular expressions.
Options Compared
\s
) using the split()
method. The first substring is then extracted and converted back to a string.parseFloat()
function to convert the numeric part of the input string to a floating-point number.[-\\d.]*
) that are either digits (\\d
), dot (.
), or hyphen (-
). The matched string is then extracted and converted back to a string.Pros and Cons
Library Used
None in this specific benchmark, as all tests are performed using built-in JavaScript functions.
Special JS Features or Syntax
There is no special JavaScript feature or syntax used in these tests. The focus is on comparing the performance of different approaches to extract a number from a string.
Other Alternatives
In addition to the three approaches mentioned above, there are other methods to extract numbers from strings, such as:
parseInt()
: Similar to parseFloat()
, but uses integer arithmetic instead.match()
with a more complex regular expression: Can be used to extract more specific types of numeric values (e.g., integers only).These alternatives may offer better or worse performance depending on the use case, but are not compared in this benchmark.