Archived

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

apocalexiz

access on a matrix, wich way is faster?

Recommended Posts

apocalexiz    122
hy there ok, i know two ways to create a matrix. The "most" general way. Allocating one big part of the memory and accessing the elements with [elem_row+elem_colum*row]. The second is with pointer to pointers and so on. So i''m able to access the array with the foo[x][y] notation. Now what is faster? I know on one hand there is a multiplication and an addition and on the other hand there is one more memory access. On very big matrices i bet the second way is faster. But i dont know thats why i''m asking. thx for help bye apo

Share this post


Link to post
Share on other sites
Sneftel    1788
The first is very slightly faster, on most architectures. It''s also less likely to have cache misses, assuming you iterate through the array in a linear fashion.

Don''t worry about it for now, tho. If matrix access turns out to be your program''s bottleneck (and trust me, it won''t) you can futz with it then. Preemptive optimization is the root of all evil.


How appropriate. You fight like a cow.

Share this post


Link to post
Share on other sites
daerid    354
you could just create a simple bounds-checked template class and be done with it:


    
#include <cassert>

template<typename T,unsigned int W,unsigned int H>
class matrix
{
public:
T& operator()(unsigned int x,unsigned int y)
{
assert((x < W) && (y < H));
return m_array[x][y];
}
private:
T m_array[W][H];
};



[edited by - daerid on March 18, 2003 12:23:54 PM]

Share this post


Link to post
Share on other sites
kdogg    204
Those are exactly the same. Internally, a 2 dimensional array is just a single dimensional array in which the compiler performs the [elem_row+elem_colum*row] math for you. It is not the same as say

int **matrix;

where you have a pointer to pointers. At least, this is how it worked when i went to school. For graphics, i generally just use a single dimensional array since nearly every matrix i use is 4x4.

Share this post


Link to post
Share on other sites