On Wed, Dec 22, 2010 at 7:46 AM, YANG Xudong <wyver...@gmail.com> wrote:
> On Tue, Dec 21, 2010 at 20:54, jemptymethod <jemptymet...@gmail.com> > wrote: > > What is "out-smarting" the compiler, really? I often get criticized > > for the following style of for loop: > > > > for (var i=0, n=arr.length; i<n; i++) > > > Why do that when the compiler does it for you, and probably in a better > way? It's totally reasonable for a compiler to try to optimize a normal > for-loop written like > > for (i = 0; i < arr.length; i++) // where i is defined somewhere by a var > statement > > because it's the most used form of for-loops. Just for example, it could > check _very specifically_ if the second part of the statement is of the form > "X < Y.length", and if so, cache the length of the array _internally_. It > might even be faster than you doing the caching manually in that your way > might introduce more overhead involving eg. creating symbol table entries. > I'm not sure about that, but I'm just trying to prove that you consciously > doing some sort of optimization does not necessarily result in better > performance than not doing it. > Actually, you/it can't optimize that case that way. The .length property might change so the length property must be checked at every iteration by the environment. That's why `for (i=0,n=a.length; ..` has absolutely nothing to do with compiler optimization. Also, note that `a.length` is not really expensive, unless `a` is something like a "live dom query". But on regular arrays, it's really about as cheap as they come. Note that it's very hard, if not impossible, in most cases to determine whether the length property of an array could be changed in the loop-body. Especially with the use of getters/setters (but even without). (Just as Poetro points out) - peter -- To view archived discussions from the original JSMentors Mailman list: http://www.mail-archive.com/jsmentors@jsmentors.com/ To search via a non-Google archive, visit here: http://www.mail-archive.com/jsmentors@googlegroups.com/ To unsubscribe from this group, send email to jsmentors+unsubscr...@googlegroups.com