在JavaScript中将字符串泛化为int转换技术

时间:2014-02-24 06:43:38

标签: javascript string-parsing base-n

我正在寻找更快的parseInt()

替代品

我最近发现了这种在JavaScript中将基数为10的数字字符串转换为int的技术:

var x = "1234567890" - 0 ;

当然,这仅限于10号。我想知道是否有任何方法可以将此概括为任何基础,同时保持效率。感谢。

有些相关,但与问题没有直接关系: 我进行了一些测试,将其性能与内置parseInt()函数进行比较。 -0方法快15~16倍。


修改

这是我正在使用的基准测试代码,控制台输出如下所示。显然,“1234”+ 0是最快的。

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);

控制台:

[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

1 个答案:

答案 0 :(得分:3)

如果您正在寻找通用解决方案,则需要使用parseInt()

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

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

请注意,虽然radix参数是可选的,但总是包含它是一个好习惯,即:

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

如果您只查找基数为10和基数为16的转化次数:

+"1234" // 1234
+"0xf" // 15