dfasdfasdfasdfasdf

JavaScript performance comparison

Test case created by sbking

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  const makeList = () => {  
  const items = [];
    for (let i = 0; i < 1000000; i++) {
      items.push(Math.random() * 1000);
    }
    return items;
  }
    
    const sortMedian = () => {
      const items = makeList();
      const sorted = items.sort((a, b) => a - b);
      return sorted[Math.floor((items.length - 1) / 2)];
    }
    
    const swap = (items, a, b) => {
      if (a === b) return;
      const temp = items[b];
      items[b] = items[a];
      items[a] = temp;
    }
    
    const pivotRandom = (_, __, left, right) => left + Math.floor(Math.random() * (right - left));
    
    const partition = (
      compare,
      items,
      left = 0,
      right = items.length,
      pivotFn = pivotRandom
    ) => {
      const pivotIndex = pivotFn(compare, items, left, right);
      const pivot = items[pivotIndex];
      swap(items, pivotIndex, right - 1);
    
      let l = left;
      let r = right - 1;
      while (r > l) {
        const item = items[r - 1];
        if (compare(item, pivot) > 0) {
          items[r] = item;
          r--;
        } else {
          swap(items, l, r - 1);
          l++;
        }
      }
      items[r] = pivot;
      return r;
    };
    
    const quickSelect = (
      compare,
      items,
      index
    ) => {
    let left = 0;
    let right = items.length;
  
    while (right > left + 1) {
      const pivot = partition(compare, items, left, right);
      if (index === pivot) {
        return items[index];
      } else if (index < pivot) {
        right = pivot;
      } else {
        left = pivot + 1;
      }
    }
  
    return items[left];
    };
    
    const quickMedian = () => {
      const list = makeList()
      return quickSelect(
        (a, b) => a - b,
        list,
        Math.floor((list.length - 1) / 2)
      );
    };
  

};
</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
sort
console.log('sort', sortMedian());
pending…
quick
console.log('quick', quickMedian());
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