Pooria Azimi
Pooria Azimi

Reputation: 8643

Optimize CoffeeScript-generated JS for V8

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...

Upvotes: 2

Views: 398

Answers (1)

Talya
Talya

Reputation: 19347

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.

Upvotes: 3

Related Questions