3 ms·
Same in JS. I once worked with someone who would use [].forEach and didn't like for loops because functional good, iterative loops bad. It was essentially in th
by jraph 2y ago
Same in JS. I once worked with someone who would use [].forEach and didn't like for loops because functional good, iterative loops bad. It was essentially in the coding style of the project and the for version would be rejected in MRs.
I don't miss this.
IMHO [].forEach just essentially expresses the same thing as a regular for loop, although in a more verbose and convoluted way that is also likely very inefficient because a JS compiler probably can't optimize away the function call per iteration, because of the very dynamic nature of JS. forEach probably has its use when you specifically need to call an existing function on each element, but I don't otherwise see the appeal.
- lupire 2y agoYou are making a strong evidence-free claim about what JS compilers don't do. https://stackoverflow.com/questions/9981607/array-foreach-running-faster-than-native-iteration-how https://stackoverflow.com/questions/9981607/array-foreach-ru...
- Teckla 2y agoAt $WORK we use Mozilla Rhino for some JavaScript processing. We tested the normal loop vs. the clever loop. Performance-wise, the normal loop blew the doors off the clever loop.
- MrJohz 2y agoRhino is a very uncommon engine though. It has its niche, but if you're developing for simpler engines like that, then you typically know that in advance and know what considerations you're going to need to make for that. When it comes to performance, lessons that apply to Rhino are unlikely to apply to more mainstream engines. EDIT: That's not to say that everyone should use map and forEach all the time, just that your benchmarks are unlikely to be relevant to most JS devs outside of your specific use-case.
- jraph 2y agoYou call "strong claim" something I prefixed with "probably"? It seems for loops in your link can be slower because .length (a function in disguise) is repeatedly called. I do save .length when writing JS. .length calls has been hard to optimize and it can't hurt too much to cache it at the start of the loop. Now it's good news if today's engines are able to optimize most of .forEach. The amount of optimization JS engines can do never ceases to amaze me and yes, any performance claim in JS needs to be constantly reviewed and checked at the time it is discussed. You can't take a "probably" as gospel. Still, it was a bit lazy of me to not re-check, I guess being called out was warranted.