parseInt() vs unary operator (v9)

Revision 9 of this benchmark created on


Description

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

  • Using parseInt(string, radix) - don't forget the radix!
  • Using a unary plus, like this: var myNumber = +myString;

This test compares the speed of each.

Setup

var stringNumbers = [];
    var naturalNumbers = [];
    var i;
    for (i = 0; i < 10; ++i) {
    stringNumbers.push("" + Math.floor(Math.random()*100));
    naturalNumbers.push(Math.floor(Math.random()*100));
    }
    var numbers = [];

Test runner

Ready to run.

Testing in
TestOps/sec
unary
var i;
for (i=0; i < 10; ++i) {
numbers.push(+stringNumbers[i]);
}
ready
natural
var i;
for (i=0; i < 10; ++i) {
numbers.push(naturalNumbers[i]);
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.