I’m currently working on a top down tile based game, and when I came to generating the map on the screen from a one dimension array, I thought of a few ways to do it. The first way was a very simple one I saw online. It involves looping through columns, and then looping through rows within columns to get coordinates. No math beyond simple addition is required to make this work.

1 2 3 4 5 6 7 8 9 10 |
var r = 0; var c = 0; while (r < rows) { c = 0; while (c < cols) { c++; } r++; } |

That’s pretty easy, right? I started to think there might be a better way to accomplish it without using two loops. I came up with a fairly simple algorithm to take care of it (I’m sure I’m not the first person to come up with it, but I did come up with it on my own). The second example requires a little bit more math, but still nothing too complex.

1 2 3 4 5 6 |
while (i < mapLength){ var x = (i % cols); var y = Math.floor(i / cols); i++; } |

I was pretty happy with that last example, it’s still very simple, and in my mind, one loop is better than two, right? I started thinking though, how much overhead is introduced by using math functions? Is it enough to offset the cost of an additional loop?

I put together a simple test at jsPerf to find out. The results blew me away.

Wow. I didn’t expect that big of a difference, but there it is. I hope this helps people who want to do tiled map generation. Also, if you have a faster way, please comment and let me know what it is!

very elegant and speedy @snollygolly!!