I have a game and initializing a map 2000 x 4000 blocks.
It runs only once onLoad and takes ~700ms. How can I speed it up? Other logic depends on this map.
Here is the code:
var start = new Date();
var g = {};
g.world = { h:2000, w:4000, cellInfo: [] };
var i, j,
world = g.world,
hlim = world.h,
wlim = world.w,
cellInfo = world.cellInfo;
for ( i = hlim; i; i--) {
cellInfo[i] = [];
for (j = wlim; j; j--) {
cellInfo[i][j] = 1;
}
}
g.world.cellInfo = cellInfo;
alert(new Date() - start);
Here is fiddle: http://jsfiddle.net/NSX9z/
A couple of options for you:
Lazy init
Your best bet for speeding it up is to use lazy initialization instead. E.g., instead of initializing all 8 million slots, have the code the relies on them handle it if they’re not there. E.g., to get a cell
…and similar for
setCell. That spreads out the init. Of course, it means things are slightly slower, though it’s unlikely to be a perceptible difference.Array cloning
If you don’t do that, another option is to create the 4,000-slot array once, then clone it rather than creating it by hand, in hopes that doing the work inside the JavaScript engine is faster than doing the actual loop yourself:
Array cloning speeds things up dramatically for me, Chrome goes from ~780ms to ~130ms, IE9 from ~530ms to ~50ms.
The other issue to consider is that on IE8 and earlier, the “slow script warning” isn’t based on time, but on number of operations. Your fiddle gives me the slow script warning on IE8. Mine doesn’t.
IE8 argues for lazy-init, though, as it takes nearly 9 seconds to run even my version of the fiddle.