While making those two JavaScript contour prototypes I posted yesterday, I had the chance to try out the nice functional programming tools offered by MochiKit. I love MochiKit—mostly because it's highly influenced by Python.

However, since the performance of the contour mapping code is extremely important to its feasibility, I did some profiling and was a bit surprised.

Consider this code to test membership in an array of points:

var containsPoint = function (container, element) {
    for (var i = 0; i < container.length; i++) {
        if (pointsEqual(container[i], element)) {
            return true;
        }
    }
    return false;
}

Boring, right? Now the functional equivalent:

return some(container, partial(pointsEqual, element));

some and partial come from MochiKit.Base and MochiKit.Iter, respectively.

Sadly, I profiled the functional approach at being 27 times slower than the verbose version.

Similarly, this code:

var neighbors = new Array();
for (var i = 0; i < points.length; i++) {
    var p = points[i];
    if (is_neighbor(scale, prev, p)) {
        neighbors.push(p);
    }
}

...is 3 times faster than this code:

var neighbors = filter(partial(is_neighbor, scale, prev), points);

I assume this has something to do with the functional approach being run as "pure JavaScript" while the verbose version is optimized by the implementation—like pure-Python vs. Python written to take advantage of its C implementation (the "pure" version being slower).

I think a lot of people don't profile their JavaScript code, so I'm just throwing this out there. Unless someone can point out a solution to the dramatic speed difference, I will sadly be avoiding a lot of the functional tools offered by MochiKit.

I'll be spending the next few days moving into my Village apartment.

Tomorrow: The final day of Summer of Code, I'll talk about my results.