Casting a string to int

JavaScript performance comparison

Revision 4 of this test case created by Esailija

Preparation code

<script>
var unparsedValues = [1,2,3,4,5,6,7,8,9,10].map(function(v){
    return v + ""
});

function doubleTilde(unparsed) {
    return ~~unparsed;
}

function parseInteger(unparsed) {
    return parseInt(unparsed, 10);
}

function multiplication(unparsed) {
    return unparsed * 1;
}


var l = 200;

while (l--) {
    for (var i = 0, len = unparsedValues.length; i < len; ++i) {
        if (doubleTilde(unparsedValues[i]) !== (i + 1)) {
            throw new Error("cheater");
        }
    }

    for (var i = 0, len = unparsedValues.length; i < len; ++i) {
        if (parseInteger(unparsedValues[i]) !== (i + 1)) {
            throw new Error("cheater");
        }
    }

    for (var i = 0, len = unparsedValues.length; i < len; ++i) {
        if (multiplication(unparsedValues[i]) !== (i + 1)) {
            throw new Error("cheater");
        }
    }
}
</script>
<script>
Benchmark.prototype.setup = function() {
    var unparsedValues = window.unparsedValues;
};
</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
With double tilde
for( var i = 0, len = unparsedValues.length; i < len; ++i ) {
    if(doubleTilde(unparsedValues[i]) !== (i + 1)) {
        throw new Error("cheater");
    }
}
pending…
With multiplication
for( var i = 0, len = unparsedValues.length; i < len; ++i ) {
    if(multiplication(unparsedValues[i]) !== (i + 1)) {
        throw new Error("cheater");
    }
}
pending…
With parseInt
for( var i = 0, len = unparsedValues.length; i < len; ++i ) {
    if(parseInteger(unparsedValues[i]) !== (i + 1)) {
        throw new Error("cheater");
    }
}
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