Archived

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

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 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 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]