array sort perform

JavaScript performance comparison

Test case created by happyWang

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  var arr = [],
      arr2 = [],
      arr3 = [],
      arrLen = 1000,
      i = 0;
  
  function makeWord(){
      var word = [],
          words = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'],
          wordsLength = words.length,
          arrMinLen = 3,
          arrLen = arrMinLen + Math.floor( Math.random()*9 ),
  
          i = 0;
  
      for (i = 0; i < arrLen; i++){
          word.push( words[Math.floor( Math.random()*wordsLength )] );
      }
  
      return word.join('');
  }
  
  // 三个一模一样的数组
  for (i = 0; i < arrLen; i++) {
      arr.push( makeWord() );
      arr2.push( makeWord() );
      arr3.push( makeWord() );
  }
  

};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
未优化
arr.sort(function(a, b){
    return +(a.toLowerCase() > b.toLowerCase()) || +(a.toLowerCase() === b.toLowerCase())-1;
});
pending…
map优化
var mapped = arr2.map(function(el, i) {
  return { index: i, value: el.toLowerCase() };
})

// 排序这个已经计算后的临时数组
mapped.sort(function(a, b) {
  return +(a.value > b.value) || +(a.value === b.value) - 1;
});

// 根据位置信息 对应映射生成一个排序后的数组
var result = mapped.map(function(el){
  return arr2[el.index];
});
pending…
不支持map的时候的兼容方法
var tmpArr = [],
    result = [],
    i = 0,
    len = arr3.length;

for (i = 0; i < len; i++) {
    tmpArr[i] = {index: i, value: arr3[i].toLowerCase()};
}

tmpArr.sort(function(a, b) {
  return +(a.value > b.value) || +(a.value === b.value) - 1;
});

for (i = 0; i < len; i++) {
    result[i] = arr3[tmpArr[i].index];
}
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 Comments