my quicksort vs array.sort

JavaScript performance comparison

Revision 2 of this test case created by andymensional

Preparation code

Benchmark.prototype.setup = function() {
    function Particle() {
    this.x = Math.random()*400;
    this.y = Math.random()*400;
    this.z = Math.random()*400;
    function qSort(array, start, end) {
      if (start < end) {
        var pivotIndex = (start + end) >> 1;
        var pivotValue = array[pivotIndex].z;
        var tmp = array[pivotIndex];
        array[pivotIndex] = array[end];
        array[end] = tmp;
        var pivotIndexNew = start;
        for (var i = start; i < end; i++) {
          if (array[i].z < pivotValue) {
            tmp = array[i];
            array[i] = array[pivotIndexNew];
            array[pivotIndexNew] = tmp;
        tmp = array[pivotIndexNew];
        array[pivotIndexNew] = array[end];
        array[end] = tmp;
        qSort(array, start, pivotIndexNew-1);
        qSort(array, pivotIndexNew+1, end);
    var part1 = [];
    var part2= [];
    var part3= [];
    for (var i = 0; i <1000; i++){
    part1.push(new Particle());
    part2.push(new Particle());
    part3.push(new Particle());

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
part1.sort(function(a,b){return a.z-b.z});
my quicksort
array.sort with >
part3.sort(function(a,b){return a.z>b.z});

Compare results of other browsers


You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

1 comment

Chris commented :

I was wondering why QS is not the default implmentation in JS - seems b/c QS is not stable. JS uses MergeSort AFAIK, which is. Interesting stuff.

Add a comment