parseInt() vs unary operator

JavaScript performance comparison

Test case created by Joshua Conner

Info

There are two ways (I know of) to cast values to number in JS:

This test compares the speed of each.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var stringNumbers = [];
    var i;
    for (i = 0; i < 10; ++i) {
    stringNumbers.push("" + Math.floor(Math.random()*100));
    }
    var numbers = [];
};
</script>

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
var i;
for (i=0; i < 10; ++i) {
numbers.push(+stringNumbers[i]);
}
pending…
parseInt
var i;
for (i=0; i < 10; ++i) {
numbers.push(parseInt(stringNumbers[i], 10));
}
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