These code motion/strength reduction optimizations are standard even in mildly optimizing compilers. I would be very surprised if an optimizing JavaScript compiler did not perform them automatically.
I tried a few micro-optimizations, but they did not make a measurable difference, so I kept the code short instead. But maybe some JIT is particularly bad at loop hoisting, so it might make a difference there.
- Move the "y * width" calculation outside of the "for x" loop.
- The multiply operators can be replaced with addition e.g. replace "y * width" with "counter += width" each y iteration and similarly for the x loop.
Optimising inner loops is really fun.
How much of the speed up in the article is because the JS engine can't figure out how to optimise it compared to the WebAssembly compiler?