2

coffee-generated JS of the following simple code snippet:

console.log 'b' if 'b' in arr

is

var __indexOf = [].indexOf || function(item) {
    for (var i = 0, l = this.length; i < l; i++) {
        if (i in this && this[i] === item) return i;
    } return -1;
};

if (__indexOf.call(arr, 'b') >= 0) {
  console.log('b');
}

I can understand why it is so. IE doesn't support indexOf, and we want to make sure our CS code runs smoothly on all browsers. But, when writing the code for a Node.js server, we know exactly what the JS engine supports (ECMA-262, 5th edition), so we wouldn't need the above trick.

I'm not terribly familiar with different JavaScript implementations, but I'm sure it's not the only non-optimal code coffee -c produces because of browser incompatibilities, and if we consider all of them in a production server with thousands of concurrent connections, they add a considerable unnecessary overhead to the code.

Is there a way to remedy this? More and more Node.js code is written in CS these days, and with SourceMap on the horizon, the number would be even greater...

1 Answer 1

3

This is barely non-optimal; the __indexOf declaration is evaluated once, at the beginning, and it's immediately resolved to [].indexOf, i.e. using the underlying implementation's Array.prototype.indexOf. That's not exactly a huge expense, surely.

I'd need to see some other examples of "non-optimal" code, but I'm sure most of them fall into the same basket. Number of concurrent connections doesn't scale the effect of this at all.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. I'm not really familiar with how JS interpreters work under the hood, and didn't know that the above resolution needs to be done only once. I guess it has something to do with JS being prorotype-based... In that case, you're right that it's really a non-isuue and doesn't scale.
It's not that it's prototype-based, but rather the assignment __indexOf = [].indexOf || … will only happen once—when the assignment is executed. At any rate, there's unlikely to be any perf difference between __indexOf.call(x, y) and x.indexOf(y)—in fact, I'd imagine the former might be faster, because it doesn't require looking up in x's prototype chain (!). So, if anything, CoffeeScript is giving you an optimisation. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.