采样数组具有良好的性能

时间:2014-08-30 12:19:02

标签: javascript performance

我有一个函数,它接受一组值和一个采样率。该函数应按采样率随机删除值。例如,20%的采样率应该消除20%的值。如何以非常好的性能实现这一目标,因为我将迭代超过10,000个值?

我的想法就像是

for(var i = values.length-1; i >= 0; i--){
    var rnd = Math.floor((Math.random() * 100) + 1);
    if(rnd < samplingRate)
        values.splice(i,1);
}

但我认为Math.random()函数不是高性能的选择。

2 个答案:

答案 0 :(得分:1)

如果你只想操作它的20%,那么真的没有必要遍历整个阵列。
循环 n n = Math.floor(0.20 * originalArray.length) - 1和每次迭代get a random element from the array并删除它。

答案 1 :(得分:1)

除非您需要支持旧浏览器,否则请使用.filter()方法:

var samplingPercentage = samplingRate / 100;

var filtered = values.filter(function() {
  return Math.random() < samplingPercentage;
});