Performance of various ways to convert strings to numbers

JavaScript performance comparison

Revision 2 of this test case created

Info

Compares the performance of various ways of converting strings to numbers:

Note that only parseInt is appropriate for user-entered numbers because you can (and should) specify the radix. But the others are handy for values you've stored in attributes and such. For this reason, parseInt here is used without the radix.

Also note that parseInt without a radix will not always give the same result as the unary operator or Number function, in the case of numbers with leading zeroes like 010. (On some implementations, parseInt will treat that as octal.)

Preparation code

<div id="theDiv" data-val="20"></div>
<script>
  var str = document.getElementById("theDiv").getAttribute("data-val");
  var n;
</script>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Unary operator +
n = +str;
pending…
Number function
n = Number(str);
pending…
parseInt sans radix
n = parseInt(str);
pending…
parseInt with radix
n = parseInt(str, 10);
pending…
Multiply by 1
n = str*1;
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment