2-dimensional array on heap, which version is faster?

亡梦爱人 提交于 2019-12-13 17:01:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!