I’d like to know which of the below methods could be considered more efficient.
The first one is quite simple it uses two for loops. The last one is my personal favorite, because it only uses one. I’m not quite sure about the pros and cons of each method though, as they are both pretty fast.
They are meant to be used with a CanvasPixelArray or ones that are structured in a similar way.
w and h stands for the width and height of the 2d matrices.
for (var y = 0; y < h; y++) {
for (var x = 0; x < w; x++) {
// ...
}
}
for (var i = 0, l = w*h; i < l; i++) {
var x = i%w;
var y = Math.floor(i/w);
// ...
}
The first will be more efficient. Think about the number of operations you are doing in the first method: One single incrementation per pixel plus an additional incrementation per row. The other method saves the extra incrementation per row but replaces it with something far more complex. In addition to the rounding and the
%which are expensive, theyvalue is recalculated each and every time, whereas it is only calculated once per row in method 1. In short, the extra incrementation per row will be far quicker than adding all these supplementary operations per pixel. This isn’t to say that you shouldn’t use the second method, but given the code you have posted the first will perform better.