本文提供兩種將陣列隨機重排(洗牌)的方法,並實際測量它們的執行效能,讓你直觀看出差異。
<script> var count = 100000,arr = []; for(var i=0;i<count;i++){ arr.push(i); } //常規方法,sort() var t = new Date().getTime(); 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); </script> 第一種是直覺的 sort() 做法,透過隨機比較函式打乱順序;第二種則是效率最高的 shuffle(),也就是 Fisher-Yates 洗牌演算法——它從陣列尾端往前遍歷,每次隨機挑一個位置與當前元素交換。相較於 sort 需要頻繁呼叫比較函式,洗牌演算法只需一次線性遍歷,效能明顯更優,而且在十萬筆資料的量級下差距會非常顯著。