Conversion of strings to numbers (v7)

Revision 7 of this benchmark created on


Description

There are some ways to cast value in strings to numbers in JS:

  • Using parseInt(string, radix) - don't forget the radix!
  • Using a unary plus, like this: var myNumber = +myString;
  • Using the Number() constructor
  • Using JSON.parse
  • Using * operator : str * 1
  • Math.floor

This test compares the speed of each.

Setup

var stringNumbers = [];
    var i;
    for (i = 0; i < 10; ++i) {
    stringNumbers.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
parseInt
var i;
for (i=0; i < 10; ++i) {
numbers.push(parseInt(stringNumbers[i], 10));
}
ready
Number
var i;
for (i=0; i < 10; ++i) {
numbers.push(Number(stringNumbers[i]));
}
ready
JSON.parse
var i;
for (i=0; i < 10; ++i) {
numbers.push(JSON.parse(stringNumbers[i]));
}
ready
* 1
var i;
for (i=0; i < 10; ++i) {
numbers.push(stringNumbers[i] * 1 || 0);
}
ready
Math.floor
var i;
for (i=0; i < 10; ++i) {
numbers.push(Math.floor(stringNumbers[i]));
}
ready

Revisions

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