Arrays, single vs multi dimensional
Which is more efficient, single or multi dimensional arrays? Is single dimension faster or multi? Which is better from game developments?
The thing here is that you need to be aware of the hidden cost of using multi-dimensional arrays, since an access to an element will (depending on the size of the array) use a multiply-instruction, the following is pretty equivalent:
The thing is that while looping through the array the second can be optimized pretty easy and without making the code very ugly:
Thus I''d say one-dimensional are faster.
char MyArray1[10][10];MyArray1[5][6] = ''a'';// andchar MyArray2[100];MyArray2[5 * 10 + 6] = ''a'';
The thing is that while looping through the array the second can be optimized pretty easy and without making the code very ugly:
for(i = 0; i < 10; i++) for(j = 0; j < 10; j++) if(j == 5) MyArray1[i][j] = ''b''; else MyArray1[i][j] = ''a'';// andint offset = 0;for(i = 0; i < 10; i++){ for(j = 0; j < 10; j++) if(j == 5) MyArray2[offset + j] = ''b''; else MyArray2[offset + j] = ''a''; offset += 10; // the ''width'' of the 2d-array}
Thus I''d say one-dimensional are faster.
January 23, 2001 11:59 AM
amag, I ran performance tests on both your one-dimensional and two-dimensional arrays, and the two-dimensional array was faster.
vbisme, I''d use two-dimensional arrays. You MAY be able to trim a few extra ms by using a one-dimensional array but it just isn''t worth the effort. You won''t notice any speed increase from using one-dimensional arrays in place of two, and it will needlessly complicate the code.
There are many other areas in your code that you will benifit more from optimizing.
vbisme, I''d use two-dimensional arrays. You MAY be able to trim a few extra ms by using a one-dimensional array but it just isn''t worth the effort. You won''t notice any speed increase from using one-dimensional arrays in place of two, and it will needlessly complicate the code.
There are many other areas in your code that you will benifit more from optimizing.
if you are gonna dynamically allocate your array, i would go with one dimensional. You can dynamically allocate a two dimensional array but the syntax to do so can get ugly and confusing.
example
i am not real sure about the second way as i havent used it in a long time but that is kinda what it looks like. The deallocation of the array is just about as ugly
"Yo yo ma"
-Kramer
example
// one dimensionalchar* array = new char[rows*cols];// two dimensionalchar** array;*array = new char[rows];for (int i = 0; i < rows; i++){ array[i] = new char[cols];}
i am not real sure about the second way as i havent used it in a long time but that is kinda what it looks like. The deallocation of the array is just about as ugly
"Yo yo ma"
-Kramer
"Yo yo ma" -Kramer
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement