0

I have an array of arrays for drawing a tilemap on the screen (basically an array of columns, each column is an array of tiles). I have tried to speed up the drawing process by not setting the array indexes that contain empty tiles, but it is not any faster.

var a1 = [];
a1[0] = 1;
a1[100] = 1;
a1[200] = 1;
a1[300] = 1;

var a2 = [];
for( var i = 0; i <= 300; i++ ) {
    a2[i] = 1;
}

When I compared the time taken to loop through these two 100,000 times, a2 was slightly faster. When I tried using ( for var x in y ) instead, both with an array and an object, they were 4 - 12 times slower.

If looping through an object is a lot slower, and removing 99% of the array (not just from the end) is not making it any faster, is there any way one could actually make it faster?

1
  • @Pete I could, but it is roughly 10 times slower. Commented Jun 2, 2014 at 9:11

1 Answer 1

2

Do not have holes in your arrays, just fill it completely (also pre-allocate to avoid dynamic resizing)

var a1 = new Array(301);
for (var i = 0; i < a1.length; ++i) a1[i] = 0;
a1[0] = 1;
a1[100] = 1;
a1[200] = 1;
a1[300] = 1;

Loop normally (never use for.in, use Object.keys if you need to iterate over keys):

for (var i = 0; i < a1.length; ++i) {
    if (a1[i] !== 0) {
        //Non empty
    }
}
Sign up to request clarification or add additional context in comments.

10 Comments

why should we avoid dynamic resizing? I usually goes with a=[] as suggesed by jshint.
@sabithpocker a resize is very expensive, all the array elements need to be copied to a new backing array. If you know the size before hand and allocate it, there will be no copying. See en.wikipedia.org/wiki/…
Ok thanks, i never knew about that. You have any link to read about this or jsperf demostrating the same?
Seems it is as good as it gets. What I wanted to achieve was looping through a1 being basically as fast as looping through any array of four elements, but it seems impossible. I wonder if changing array[key] = value to array[x] = [key, value] could be faster.
@user3358029 Actually not necessarily, CPU cache highly favors a flat array so even if there is like 300 items where 4 are filled, it wouldn't surprise me if it was faster than an array of 4 items where you need extra indirection to see what their coords are. For 10% marked squares it would be even less surprising
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.