PERF Merge Sort in JS

performance testing it and stuff

by Christopher Stephens

HTML

<div id="logger"></div>

CSS

.title {
    font-weight:bold;
    margin-top:15px;
}

JavaScript

// merge sort

// I'm using a closure/module here so that I can declare merge once and not evertime I call the internal sort
var mergeSort = (function () {
    var merge = function (sortedA, sortedB) {
        var toReturn = [];
        var itA = 0, itB = 0, 
            Alength = sortedA.length, Blength = sortedB.length;
        while(itA < Alength && itB < Blength) {
            if (sortedB[itB] < sortedA[itA]) {
                toReturn.push(sortedB[itB++]);
            } else {
                toReturn.push(sortedA[itA++]);
            }
        }
        toReturn = toReturn.concat(sortedB.slice(itB)).concat(sortedA.slice(itA));
        return toReturn;
    };

    var sort = function (toSort) {
        var arlength = toSort.length;
        var midpoint = Math.round(arlength / 2);

        if (toSort.length > 1) {
            // just here to illistrate the step, these should be remove or renamed and moved to the top of the function
            // MEMOP - slicing creates new arrays, performign this in place would be lighter
            var A = toSort.slice(0, midpoint);
            var B = toSort.slice(midpoint, arlength);
            return merge(sort(A), sort(B));
        }
        return toSort;
    };

    return sort;
})();

// BEGIN SETUP
// REMOVE these if running in something that supports console.log etc

var test = function(title, list, callA, callB){
    var timer,
        Alist = list.slice(0),
        Blist = list.slice(0);
    
    console.debug("</br>"+ title);
    console.log(list);

    console.debug("A");
    //console.log(Alist);
    timer = new Date().getTime();
    console.debug(callA(Alist));
    console.log("Milliseconds: " + (new Date().getTime() - timer));

    console.debug("B");
    //console.log(Blist);
    timer = new Date().getTime();
    console.debug(callB(Blist));
    console.log("Milliseconds: " + (new Date().getTime() - timer))
}

console.log = function (message) {
    $("#logger").append("<div>" + message +...