递归函数的奇怪jsPerf行为

时间:2012-01-29 16:46:32

标签: javascript jsperf

我在jsPerf的测试用例中有以下代码:

var arr = [0, 45, 96, 8, 69, 62, 80, 91, 89, 24, 6, 23, 49, 88, 26, 40, 87, 61, 83, 2, 60, 53, 43, 82, 67, 3, 65, 37, 42, 77, 73, 38, 9, 46, 75, 10, 63, 15, 47, 28, 79, 55, 59, 95, 11, 93, 70, 98, 25, 48, 30, 5, 72, 12, 84, 1, 29, 13, 50, 33, 19, 7, 31, 57, 32, 44, 74, 51, 35, 90, 86, 54, 4, 64, 92, 71, 22, 41, 16, 17, 27, 76, 39, 18, 99, 94, 36, 66, 85, 20, 21, 56, 34, 81, 14, 78, 68, 58, 97, 52];

Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

function quicksort( arr ) {
  if ( arr.length <= 1 ) 
    return arr;
  var i = 0, 
      len = arr.length, 
      less = [], 
      greater = [], 
      random = Math.floor( Math.random() * len ), 
      pivot = arr[ random ];
  arr.remove( random );
  for ( ; i < len - 1; i++ ){
    if ( arr[ i ] <= pivot )
      less.push( arr[ i ] );
    else 
      greater.push( arr[ i ] );
  }
  return quicksort( less ).concat( pivot, quicksort( greater ) );
};

如果将其复制到控制台并运行quicksort( arr ),您将看到它正确返回已排序的数组。

但出于某种原因,在jsPerf的this test case中,我的快速排序函数似乎只返回一个数字(可以在'Perparation Code Output'中看到)。它似乎也比它应该的运行速度更快。

任何有关正在发生的事情的人都会非常感激。

1 个答案:

答案 0 :(得分:2)

我认为问题在于你在原始数组上调用了.remove()函数,因此它会快速将其删除为空。换句话说,每次对quicksort函数的初始调用都会删除一个元素。

When I make it create a copy of the array first,然后它似乎有效。