Make sure things are contiguous in memory as cache behavior is likely to dominate the run-time of any code which performs only simple operations.
For instance, don't use this:
int* a[10];
for(int i=0;i<10;i++)
a[i] = new int[10];
//Also not this
std::vector< std::vector<int> > a(std::vector<int>(10),10);
Use this:
int a[100];
//or
std::vector<int> a(100);
Now, if you need 2D access use:
for(int y=0;y<HEIGHT;y++)
for(int x=0;x<WIDTH;x++)
a[y*WIDTH+x];
Use 1D accesses for tight loops, whole-array operations which don't rely on knowledge of neighbours, or for situations where you need to store indices:
for(int i=0;i<HEIGHT*WIDTH;i++)
a[i];
Note that in the above two loops the number of items touched is HEIGHT*WIDTH
in both cases. Though it may appear that one has a time complexity of O(N^2)
and the other O(n)
, it should be obvious that the net amount of work done is HEIGHT*WIDTH
in both cases. It is better to think of N
as the total number of items touched by an operation, rather than a property of the way in which they are touched.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…