Helpful Tools For Web Developers: JsPerf

When it comes to front-end development, performance tweaking is often a forgotten step. However, as web applications become larger and more and more complex, maintaining and tweaking the performance of your application becomes more important. Unfortunately, this is not as easy as it sounds. How do you know that the code you’ve refactored is actually more efficient than the original? That’s where tools like JsPerf come in.

JsPerfs allows you to compare the efficiency of two pieces of code. Take the following for example:

Array.prototype.loopBackward = function(searchString) {
    var me = this,
    numItems = this.length,
    i, returnArray = [];

    for (i = numItems - 1; i >= 0; i--) {
        returnArray.push(me[i]);
    }
    return returnArray;
}

Array.prototype.loopForward = function(searchString) {
    var me = this,
    numItems = this.length,
    i, returnArray = [];

    for (i = 0; i <= numItems - 1; i++) {
        returnArray.push(me[i]);
    }

    return returnArray;
}

Here I’ve added two methods to the Array object: loopForward and loopBackward. One iterates through an array from 0 to its length and the other goes from its length down to 0.

When I set these tests up in JsPerf, here’s what I found out:

jsperf-test

Looping through an array backwards is faster than looping through it forwards. With this is mind, if your application has to loop through a lot of large datasets, it would be more efficient for you to loop through them backwards.

Granted this is only a small sampling of the kinds of tests you can run on JsPerf. I highly recommend it for anyone looking for a good comparison tool to use when trying to increase the performance of their web applications.