parseInt() vs unary operator vs Number() (v17)

Revision 17 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;
  • Using Number, like this: var myNumber = Number("3")

This test compares the speed of each.

Preparation HTML

<script data-require="lodash.js@*" data-semver="3.10.0" src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.0/lodash.js"></script>

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

Revisions

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