Archived

This topic is now archived and is closed to further replies.

DrEvil

2d array efficiency

Recommended Posts

Consider the following, and correct me if I'm wrong please.
// 10x10 array for this example


#define ARRAYWIDTH 10
#define ARRAYHEIGHT 10
#define I(x,y) (y * ARRAYWIDTH + x)


// First method


// creation

int *2darray = new int[ARRAYWIDTH * ARRAYHEIGHT ];
// indexing

int element = 2darray[I(5,5)];


// Second method


// creation

int **2darray = new int*[ARRAYHEIGHT];
for(int i = 0; i < ARRAYHEIGHT; i++)
	2darray[i] = new int[ARRAYWIDTH];

// indexing

int element = 2darray[5][5];

 
It would seem to me, that method 1 would be more efficient, since you are guaranteed that the 2d array is all together in memory & is more cache friendly than method 2. Is this correct? Also, it's true that each "row" of the array in method 2 could be in completely different areas of memory right? Obviously method 2 would be slower in the allocation phase, so my question is more geared towards accessing the array after creation. Thanks [edited by - DrEvil on April 20, 2004 3:23:30 AM]

Share this post


Link to post
Share on other sites
Access would be slower, yes, because you wouldn''t have the continuous memory as you would in the first method, and thus would have to differ two pointers as opposed to one. This means you would also be using an extra pointer for each "row" in the second method. Also, allocation and deallocation are more of a hassle. But you get to use 2D array access operators on it instead of some hackified macro/function, so I suppose that''s nice.

Share this post


Link to post
Share on other sites
quote:

But you get to use 2D array access operators on it instead of some hackified macro/function, so I suppose that''s nice.



I don''t think that IS nice (although macros should be avoided). The longhand "y * ARRAYWIDTH + x" is the nicest way in my opinion.

Mark
Sound Effects For Game Developers
http://www.indiesfx.co.uk
Flatspace is here: The ultimate space adventure
http://www.lostinflatspace.com

Share this post


Link to post
Share on other sites