Showing the results of converting 30 strings to a JavaScript number 3,000 times. All times are normalized relative to parseInt(str)
; lower is better.
Method | Speed |
---|---|
parseInt(str) | calculating |
parseInt(str,10) | calculating |
parseFloat(str) | calculating |
str<<0 | calculating |
+str | calculating |
str*1 | calculating |
str-0 | calculating |
Number(str) | calculating |
Given the wild variations in times on the same computer/OS/browser/version (reload this page several times to see different answers), this page cannot make any broad claims about the performance of one technique over another. Note that, in general, you will never notice any performance difference between these. Which method you should use depends on what you need:
"1000" | "10.9" | "1,000.9" | "011" | "10c" | "$10" | |
---|---|---|---|---|---|---|
parseInt(str) | 1000 | 10 | 1 | 9 | 10 | NaN |
parseInt(str,10) | 1000 | 10 | 1 | 11 | 10 | NaN |
parseFloat(str) | 1000 | 10.9 | 1 | 11 | 10 | NaN |
str << 0 | 1000 | 10 | 0 | 11 | 0 | 0 |
+str, str*1, str-0 | 1000 | 10.9 | NaN | 11 | NaN | NaN |
Number(str) | 1000 | 10.9 | NaN | 11 | NaN | NaN |
I personally use and advocate *1
as it is short to type, but still stands out (unlike the unary +), and either gives me what the user typed or fails completely. I only use parseInt()
when I know that there will be non-numeric content at the end to ignore, or when I need to parse a non-base-10 string. I will sometimes use num = num << 0
when I need to truncate a number faster than Math.floor()
, but never to convert a string to a number.