Performance of various ways to convert strings to numbers
JavaScript performance comparison
Info
Compares the performance of various ways of converting strings to numbers:
- The unary operator (
+str) - The
Numberfunction parseIntwith a radixparseIntwithout a radix
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.
| Test | Ops/sec | |
|---|---|---|
Unary operator + |
|
pending… |
Number function |
|
pending… |
parseInt sans radix |
|
pending… |
parseInt with radix |
|
pending… |
Multiply by 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:
- Revision 1: published by T.J. Crowder
- Revision 2: published
0 comments