Question

I'm looking for a faster alternative of parseInt()


I recently found out this technique of converting a base 10 numeric string into an int in JavaScript:

var x = "1234567890" - 0 ;

Of course, this is restricted to base 10. I would like to know if there is any way of generalizing this to any base while preserving the efficiency. Thanks.

Somewhat relevant, but not directly related to the question: I ran a little test to compare its performance with the built-in parseInt() function. The -0 method is 15~16 times faster.


EDIT:

Here is the benchmarking code I'm using, and the console output is bellow it. Apparently, "1234"+0 is the fastest one.

var n = 1000000 ;
var x;

//parseInt with radix 10
t0 = Date.now(); console.log(t0);
for(i=0; i<n; i++) {
    x = parseInt("1234567890", 10) ;
}
t1 = Date.now(); console.log(t1);

console.log(t1-t0);


//parseInt without specifying the radix
t0 = Date.now(); console.log(t0);
for(i=0; i<n; i++) {
    x = parseInt("1234567890") ;
}
t1 = Date.now(); console.log(t1);

console.log(t1-t0);


//using - 0 to convert string to int
t0 = Date.now(); console.log(t0);
for(i=0; i<n; i++) {
    x = "1234567890" - 0 ;
}
t1 = Date.now(); console.log(t1);

console.log(t1-t0);

//using =+ to convert string to int
t0 = Date.now(); console.log(t0);
for(i=0; i<n; i++) {
    x = +"1234567890" ;
}
t1 = Date.now(); console.log(t1);

console.log(t1-t0);

Console:

[01:58:05.559] 1393225085558
[01:58:05.623] 1393225085622
[01:58:05.623] 64
[01:58:05.623] 1393225085623
[01:58:05.683] 1393225085683
[01:58:05.684] 60
[01:58:05.684] 1393225085684
[01:58:05.689] 1393225085689
[01:58:05.689] 5
[01:58:05.689] 1393225085689
[01:58:05.786] 1393225085786
[01:58:05.786] 97
Was it helpful?

Solution

If you're looking for a generic solution, you will want to use parseInt():

var x = parseInt("1234567890"); // automatic base detection

var x = parseInt("777", 8); // force octal base (511)

Note that although the radix argument is optional, it's a good practice to always include it, i.e.:

parseInt("09"); // may fail
parseInt("09", 10); // always 9

If you're only looking for base-10 and base-16 conversions:

+"1234" // 1234
+"0xf" // 15
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top