News for hackers. Stuff that matters.
Re:“Clean” Code, Horrible Performance by gardenhedge on Tuesday February 28, 2023 @06:54PM (#34976670)
I'd be interested in a blog post on this. Why is JS map so much slower than a for loop?
Re:“Clean” Code, Horrible Performance by Veliladon on Tuesday February 28, 2023 @08:19PM (#34977500)
So normally when you do a bunch of patterns of .filter(), and/or .map(), and/or .reduce() on an array in most other languages the compiler will normally iterate through the elements doing whatever you requested at each element. No allocations, one quick trip through the entire working set, cache locality works no matter how big the set is.

In JavaScript on the other hand it handles the abstraction by constructing a separate function for each pattern you use. In those functions it allocates an array the same size as the working set, iterates through each element, then returns the new array. If you're doing multiple operations at once this means that you have to have multiple allocations and multiple iterations through the entire working set.

Because it's doing an allocations it's basically doing an extra memcpy for each additional pattern past one which is a giant slowdown. Then if the working set is too big for the L2 cache it needs to be reloaded from L3 each loop. If the working set is too big for L3 then it needs to reload from main memory EACH TIME.

If you wanted to implement patterns as slow as molasses I can think of no better way than to sugar it out like JavaScript did.

Re:“Clean” Code, Horrible Performance by jimbokun on Tuesday February 28, 2023 @10:02PM (#34978250)
Interesting. Is there something about JS semantics that prevents JS engine writers from better optimizing that pattern?
Re:“Clean” Code, Horrible Performance by Veliladon on Wednesday March 01, 2023 @12:46AM (#34979189)
Short answer: JavaScript arrays are sparse and untyped.
Re:“Clean” Code, Horrible Performance by david2ndaccount on Tuesday February 28, 2023 @08:33PM (#34977609)
Approximately, the slowest thing you can do in a program is memory allocation (and garbage collection is even slower). JS map allocates an entire new array.