3 ms·
I think nearly every JS engine now optimizes `for (...;i < arr.length;...)` -- I'm nearly 100% sure V8 does and fairly certain Firefox's and ModernIE's do as we
by pluma 12y ago
I think nearly every JS engine now optimizes `for (...;i < arr.length;...)` -- I'm nearly 100% sure V8 does and fairly certain Firefox's and ModernIE's do as well.
In fact, even `for` is likely an over-optimization. In nearly all JS code you can get away with just using `forEach` (or its friends).
- thomasfoster96 12y agoforEach is awfully slow compared to a for statement if you're dealing with numbers - less so with strings/objects, but it's still noticeable (like 10x whenever I've tested it at best). Caching the array length still gives you a small speed boost in most browsers, but it's probably an over optimisation unless you're doing something really intensive.
- jaredsohn 12y agoI think a big reason to cache the array length within interviews (for cases when it isn't already cached) is that to not do so can often increase the complexity of a solution by a factor of O(n).
- pluma 12y agoIf you're doing number crunching, yes, don't use forEach. If you're just writing ordinary business code (i.e. in 80% of all code out there), by all means, please use forEach and friends. Besides, if you're doing number crunching in JS, you probably want to stick to ASM.js anyway.