Search code examples
javascriptperformancehtmlcoffeescriptbenchmarking

is coffeescript faster than javascript?


Javascript is everywhere and to my mind is constantly gaining importance. Most programmers would agree that while Javascript itself is ugly, its "territory" sure is impressive. With the capabilities of HTML5 and the speed of modern browsers deploying an application via Javascript is an interesting option: It's probably as cross-platform as you can get.

The natural result are cross compilers. The predominant is probably GWT but there are several other options out there. My favourite is Coffeescript since it adds only a thin layer over Javascript and is much more "lightweight" than for example GWT.

There's just one thing that has been bugging me: Although my project is rather small performance has always been an important topic. Here's a quote

The GWT SDK provides a set of core Java APIs and Widgets. These allow you to write AJAX applications in Java and then compile the source to highly optimized JavaScript

Is Coffeescript optimized, too? Since Coffeescript seems to make heavy use of non-common Javascript functionality I'm worried how their performance compares.

Have you experience with Coffeescript related speed issues ? Do you know a good benchmark comparison ?


Solution

  • Apologies for resurrecting an old topic but it was concerning me too. I decided to perform a little test and one of the simplest performance tests I know is to write consecutive values to an array, memory is consumed in a familiar manner as the array grows and 'for' loops are common enough in real life to be considered relevant.

    After a couple of red herrings I find coffeescript's simplest method is:

    newway = -> [0..1000000]
    # simpler and quicker than the example from http://coffeescript.org/#loops
    # countdown = (num for num in [10..1])
    

    This uses a closure and returns the array as the result. My equivalent is this:

    function oldway()
    {
        var a = [];
        for (var i = 0; i <= 1000000; i++)
            a[i] = i;
        return a;
    }
    

    As you can see the result is the same and it grows an array in a similar way too. Next I profiled in chrome 100 times each and averaged.

    newway() | 78.5ms
    oldway() | 49.9ms
    

    Coffeescript is 78% slower. I refute that "the CoffeeScript you write ends up running as fast as (and often faster than) the JS you would have written" (Jeremy Ashkenas)


    Addendum: I was also suspicious of the popular belief that "there is always a one to one equivalent in JS". I tried to recreate my own code with this:

    badway = ->
        a = []
        for i in [1..1000000]
            a[i] = i
        return a
    

    Despite the similarity it still proved 7% slower because it adds extra checks for direction (increment or decrement) which means it is not a straight translation.