问题
double **array = new double* [X];
for (int i=0; i<X; i++)
array[i] = new double [Y];
array[x][y] = n;
or
double *array = new double [X*Y];
array[x*Y+y] = n;
Second version is created faster, but access is in first version faster (e.g. image processing using convolution), isn't it? Or is it all negligible?
回答1:
In theory the second version should be faster, because the entire array is allocated contiguouslly, so its more cache-friendly than the first.
But in practice, profile it and see what happens. This kind of performance questions depends heavily on your architecture, OS, etc.
My advise here (In addition to profiling) is: Consider to use standard containers (A std::vector<std::vector<T>>
in this case) which had been profiled, tested, and also make your life easier moving you away from raw-pointers and manual memory management.
回答2:
Ok, I have: 1000x1000 image with conventional implemented Fourier transform on double arrays: Windows 7 Pro 64-bit, VC++ 2010 Express -> exactly the same (2:11 minutes)!
来源:https://stackoverflow.com/questions/20598062/2-dimensional-array-on-heap-which-version-is-faster