2

Short question:

Let's say we have jQuery included. Will this function execute faster ...

var example1 = (function($, jQuery) {
    return function() {
        // do something
    }
})()

... than the following one:

var example2 = (function() {
    return function() {
        // do something
    }
})()

?

In the first one the jQuery object will be undefined, in the second one it will be inherited. So the second one should be more expensive?

What is the best way to improve speed and get rid of inherited variables that decreases performance?

jsPerf test: http://jsperf.com/objinheritance

4

1 回答 1

3

As ECMAScript defines, reference resolution is a inner-to-outer lookup process, so in the first example, the $ variable is 1 step from your code, and in the second example, while $ resides in global scope, it is at least 2 steps away, which cause extra lookup overhead.

However, in real world, modern javascript engines (such as V8) doesn't implement reference resolution the exactly same way which ECMAScript states, they have an approach to flattern the scope chain, in other words, for most code, all variables can be referenced in a single step, no lookup overhead at all.

Conslusion: they are really same to each other.

PS: as well as the scope chain, javascript engines have quite the same optimization on prototype chain, so there is also no need to worry about a property lookup overhead.

于 2012-04-23T08:55:20.970 回答