Question

I am implementing an A Star algorithm and performance are more important than readability in this specific case.

Since my AStar.FindPath is occasionally called multiple times in a few milliseconds and good performance is mandatory, is it more efficient to have multiple Foo.Bar.Baz in it, or do var fooBaz = Foo.Bar.Baz at the beginning and have multiple fooBaz in it?

FindPath(o, d) {
    var fooBaz = Foo.Bar.Baz;
    // Multiple fooBaz
    // More code...
}

VS

FindPath(o, d) {
    // Multiple Foo.Bar.Baz
    // More code...
}
Was it helpful?

Solution

It depends on what you do with your foo.bar.baz, and the complexity of your code.

While in principle var foobaZ should be quicker, in most cases it's going to be exactly the same, as the browser is going to be smart enough to optimize your code anyway. The key thing, is that this can only happen if you don't assign to Foo.Bar.Baz (which seems the case, otherwise you wouldn't be able to replace it with a local variable).

See it for yourself, the difference is minimal (the timing error is greater than the measured difference):

http://jsperf.com/objvsvar

OTHER TIPS

var fooBaz = Foo.Bar.Baz; is definitely quicker than Foo.Bar.Baz multiple times.

I'll find a reference and update but I've always used the local reference since it doesn't have to do more lookups.

EDIT: From http://www.phpied.com/extreme-javascript-optimization/

Property Depth

Nesting objects in order to use dot notation is a great way to namespace and organize your code. Unforutnately, when it comes to performance, this can be a bit of a problem. Every time a value is accessed in this sort of scenario, the interpreter has to traverse the objects you've nested in order to get to that value. The deeper the value, the more traversal, the longer the wait. So even though namespacing is a great organizational tool, keeping things as shallow as possible is your best bet at faster performance. The latest incarnation of the YUI Library evolved to eliminate a whole layer of nesting from its namespacing. So for example, YAHOO.util.Anim is now Y.Anim.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top