2016-04-03 10 views
1

在JS中,我必須排序很多數組元素(100k-1kk)。 ('')字符串。可能有多個空白('')字符串。在array.sort中處理空字符串(?)在Chrome中的回調很慢

在我的排序功能

我處理空值 - 使這個值總是在最後。其來確定..直到我許多空或未定義或空白(「」)值數據

如果數據有很多空值或空白字符串的性能很差。

而且更主要的是,該片段在很慢(至少最後一個版本,現在49.0.2623.110米)

火狐(45.0.1)的作品非常好(甚至非標準情況沒有空數據我的測試x10更快??) 只是test.with鉻和火狐

PS我知道jsperf是that.anyway

https://jsfiddle.net/3h0gtLu2/18/

data = [] 

var i = 0; 

while (i++ <1000){ 

    data.push('' + i) 
} 

while (i++ < 20000){ 

    data.push(''+i ) 

} 

var start = window.performance.now() 
data.sort(function(a,b){ 

    if (a == null || a == undefined) 
         return 1; 
    else if (b == null || b == undefined) 
         return -1; 
    return (parseInt(a) - parseInt(b)); 
}) 

$('#time0').html($('#time0').html() + (window.performance.now() - start)) 


data = [] 

var i = 0; 

while (i++ <1000){ 

    data.push('' + i) 
} 

while (i++ < 20000){ 

    data.push(null ) 

} 

var start = window.performance.now() 
data.sort(function(a,b){ 

    if (a == '' || a === null || a == undefined) 
         return 1; 
    else if (a == '' || b === null || b == undefined) 
         return -1; 
    return (parseInt(a) - parseInt(b)); 
}) 


$('#time1').html($('#time1').html() + (window.performance.now() - start)) 


data = [] 

var i = 0; 

while (i++ <1000){ 

    data.push('' + i) 
} 

while (i++ < 20000){ 

    data.push('' ) 

} 

var start = window.performance.now() 
data.sort(function(a,b){ 

    if (a == null || a == undefined) 
         return 1; 
    else if (b == null || b == undefined) 
         return -1; 
    return (parseInt(a) - parseInt(b)); 
}) 

$('#time2').html($('#time2').html() +(window.performance.now() - start)) 

data = [] 

var i = 0; 

while (i++ <1000){ 

    data.push('' + i) 
} 

while (i++ < 20000){ 

    data.push('' ) 

} 

var start = window.performance.now() 
data.sort(function(a,b){ 

    if (a == '' || a == null || a == undefined) 
         return 1; 
    else if (b == '' || b == null || b == undefined) 
         return -1; 
    return (parseInt(a) - parseInt(b)); 
}) 
$('#time3').html($('#time3').html() +(window.performance.now() - start)) 
+2

如果您沒有發佈代碼,那麼任何人都不可能提供幫助。 – Pointy

+0

抱歉代碼發佈:) –

+0

問題是,您的排序比較功能不一致,並可能導致排序算法發瘋。對於相同的兩個值,比較器必須始終返回完全相同的答案。 – Pointy

回答

1

爲了確保您的比較總是會返回一個合乎邏輯的答案,每對值更理想,你就必須添加的情況下當兩個值爲空:

data.sort(function(a,b){ 
    var anull = (a == '' || a == null), bnull = (b == '' || b == null); 
    if (anull && bnull) 
    return 0; 
    if (anull) 
    return 1; 
    if (bnull) 
    return -1; 
    return (parseInt(a) - parseInt(b)); 
}) 

注意,你並不需要一個明確的比較都nullundefined;比較== null與比較=== null=== undefined完全相同。

我一定要告訴排序算法,當兩個值都爲空時,它們可以單獨留下(通過返回0),避免它在某些奇怪的情況下來回抖動。

另一件可能會加速的事情是將數組轉換爲單個數據以將所有空條目轉換爲單個值(可能爲null;無所謂),並將所有非空條目轉換爲實際數字。這樣你的排序不會支付一遍又一遍地將字符串轉換爲數字的價格(即,所有對parseInt()的調用)。如果你想讓數組成爲字符串,你總是可以在隨後的單次傳遞中將其轉換回來。

+0

非常感謝。 –