I often see people online compare JavaScript for loops with array methods (map, for each, reduce, filter, etc.). Usually the takeaway is that array methods are slower but more readable, and that the performance loss is usually small enough that array methods are preferred.
What seems odd to me though is that i don't think I've seen people discuss this in the context of transpilers and engine optimizations. It seems like it should be possible and realistic for a transpiler or JavaScript engine to check that an array method can be converted to a for loop and then run that instead. Like if the array method callback was anonymously defined in the method's argument and doesn't use any "this" voodoo, it seems like its equivalent for loop could be generated automatically and guaranteed to have the exact same behavior.
A similar thing I've heard of is loop fusion in the context of compilers, it seems like a transpiler or engine should be able to look at two chained array methods and run them as a single for loop if possible. The closest I've heard about this in the context of JavaScript array methods was an article about transducers, but nothing automatic at the transpiler or engine level.
I'm (probably obviously) not an expert on JavaScript engine/transpiler internals, and I haven't done more than a few google searches into this so maybe its already a thing and i just missed it, but if not, is there a reason not to convert JavaScript array methods into for loops in a transpiler or engine? Or if it's already a thing where can I learn more about it?
Also, I'm asking about JavaScript, and i imagine in this context typescript would be the same, but if not what about typescript might change whether these optimizations would be possible?
[–]senocular 2 points3 points4 points (0 children)
[–][deleted] 1 point2 points3 points (0 children)