在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))
如果您沒有發佈代碼,那麼任何人都不可能提供幫助。 – Pointy
抱歉代碼發佈:) –
問題是,您的排序比較功能不一致,並可能導致排序算法發瘋。對於相同的兩個值,比較器必須始終返回完全相同的答案。 – Pointy