簡體   English   中英

在JavaScript中將字符串泛化為int轉換技術

[英]Generalizing a string to int conversion technique in JavaScript

我正在尋找更快的替代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

如果您正在尋找通用解決方案,則需要使用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

如果您只是在尋找base-10和base-16轉換:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM