On Feb 19, 7:13 pm, Stefan Weiss <[email protected]> wrote: > On 18/02/11 17:35, bytespider wrote: > > > for (var i = 0, length = arr.length; i < length; ++i) { > ... > > Note I also use ++i over i++ because > > it's slightly faster on some modern browsers but mostly out of habit. > > Okay, now we're firmly in micro-optimization land, but I'm curious... > partially because this topic comes up once in a while, and partly > because I also tend to use ++i rather than i++ (purely out of habit). > > This used to be a sensible optimization in C once, a long time ago, but > modern compilers like gcc or javac will automatically optimize an > expression like this when its return value is not used (I've appended a > few examples in case you want to confirm it for yourself). As far as I > know, there is no longer any point in preferring pre-increment over > post-increment in a for-loop like this. Same thing goes for C++, as long > as i is a simple type. > > Now you say that modern browsers will perform _better_ when you use the > pre-incement. Did you actually test this? I tried to verify it with a > couple of modern engines, but didn't see any difference. I didn't expect > to see any - modern JS engines should have more advanced optimizers than > older ones; they should be better able to recognize that the return > value won't be used and the expression i++ can be optimized. It seems > like most modern engines do this. > > From a semantic viewpoint, some people say that ++i expresses the intent > more accurately. From a logical viewpoint, using ++i should never be > slower than i++, regardless of optimizers. From a pragmatic viewpoint - > who cares, they're both fast enough. As I said, I'm just curious. > > Before I get flamed: this is a purely academic question. I'm certainly > not suggesting it has any impact on real life JS performance from our > perspective.
This hasn't mattered since IE6 as far as I can tell. There use to be numerous detailed numbers and reviews on this: http://homepage.mac.com/rue/JS_Optimization_Techniques/ http://home.earthlink.net/~kendrasg/info/js_opt/jsOptMain.html -- To view archived discussions from the original JSMentors Mailman list: http://www.mail-archive.com/[email protected]/ To search via a non-Google archive, visit here: http://www.mail-archive.com/[email protected]/ To unsubscribe from this group, send email to [email protected]
