Alex Rivera | Logout

JavaScript, sorting with second parameter is faster

Asked 2011-08-28T12:51:12.187
18

I have made a little test, and found out that array.sort(function(a, b) { return a - b; }); is a lot faster than array.sort(); in JavaScript.

The results were quite shocking, about 1.7 times faster in IE9, 1.6 times in FF7 and 6.7 times in Chrome.

Also, by implementing quicksort by myself in JS, I found it was even faster than both methods mentioned above. (Two different implementations, one accepts a comparer function as a parameter, the other doesn't. Both were faster.)

Is there any reasonable explanation?

EDIT: My implementations:

No comparer:

function quickSort(array, from, to) {
    if(typeof from === 'undefined') {
        from = 0;
        to = array.length - 1;
    }
    else if(typeof to === 'undefined') {
        to = array.length - 1;
    }

    if(to - from < 1) {
        return;
    }

    var i = from, pivot = to, t;

    while(i < pivot) {
        if(array[i] > array[pivot]) {
            t = array[i];
            array[i] = array[pivot - 1];
            array[pivot - 1] = array[pivot];
            array[pivot] = t;
            pivot--;
        }
        else {
            i++;
        }
    }

    quickSort(array, from, pivot - 1);
    quickSort(array, pivot + 1, to);
}

With comparer:

function quickSortFunc(array, sortfunc, from, to) {
    if(typeof from === 'undefined') {
        from = 0;
        to = array.length - 1;
    }
    else if(typeof to === 'undefined') {
        to = array.length - 1;
    }

    if(to - from < 1) {
        return;
    }

    var i = from, pivot = to, t;

    while(i < pivot) {
        if(sortfunc(array[i], array[pivot]) > 0) {
            t = array[i];
            array[i] = array[pivot - 1];
            array[pivot - 1] = array[pivot];
            array[pivot] = t;
            pivot--;
        }
        else {
            i++;
        }
    }

    quickSortFunc(array, sortfunc, from, p
Edit
Report

1 Answer

0

This is quite a wild guess, but could the performance hit occur due to the native sort, checking if the attributes passed is blank or null... Hence searching up the default function on each search (instead of once)...

It could be a mistaken optimization issue, that could be resolved if true... Hopefully someone in firefox dev can answer this :)

answered 2011-08-31T15:06:53.333

Your Answer