Javascript:最高效率的数组乱序方法

常用的办法是给数组原生的sort方法传入一个函数,此函数随机返回1或-1,达到随机排列数组元素的目的。

arr.sort(function(a,b){ return Math.random()>.5 ? -1 : 1;});

这种方法虽直观,但效率并不高,经我测试,打乱10000个元素的数组,所用时间大概在35ms上下(firefox,下同)

本人一直具有打破沙锅问到底的优良品质,于是搜索到了一个高效的方法。原文见此

if (!Array.prototype.shuffle) {
    Array.prototype.shuffle = function() {
        for(var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
        return this;
    };
}
arr.shuffle();

此方法是为Array.prototype添加了一个函数,叫shuffle——不过叫什么名字不重要啦,重要的是他的效率。

拿我上面那个10000个元素的数组来测试,用这个方法乱序完成仅需要7,8毫秒的时间。

把数组元素增加10倍到100000来测试,第一种sort方法费时500+ms左右,shuffle方法费时40ms左右,差别是大大的。

完整测试代码:

View Code
var count = 100000,arr = [];
for(var i=0;i<count;i++){
    arr.push(i);
}
/**/
//常规方法,sort()
var t = new Date().getTime();
//arr.sort(function(a,b){ return Math.random()>.5 ? -1 : 1;});
Array.prototype.sort.call(arr,function(a,b){ return Math.random()>.5 ? -1 : 1;});
document.write(arr+'<br/>');
var t1 = new Date().getTime();
document.write(t1-t);

//以下方法效率最高
if (!Array.prototype.shuffle) {
    Array.prototype.shuffle = function() {
        for(var j, x, i = this.length; i; j = parseInt(Math.random() * i), x = this[--i], this[i] = this[j], this[j] = x);
        return this;
    };
}
var t = new Date().getTime();
arr.shuffle();
document.write('<br/>'+arr+'<br/>');
var t1 = new Date().getTime();
document.write(t1-t);

 

另外,弱弱的问下,大家看看shuffle里面那个for循环,他没有后半截!也就是只有for(...)没有后面的{...},我很想知道为什么可以这样写?居然可以正常执行呢。。

本文链接: http://www.jo2.org/archives/326.htm.

posted on 2012-04-23 17:08  十年灯  阅读(1340)  评论(6编辑  收藏  举报