堆2维数组,该版本是更快? [英] 2-dimensional array on heap, which version is faster?

查看:114
本文介绍了堆2维数组,该版本是更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

double **array = new double* [X];
for (int i=0; i<X; i++)
    array[i] = new double [Y];

array[x][y] = n;

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?

推荐答案

在理论上的第二个版本应该会更快,因为整个数组contiguouslly分配的,所以比第一它更多的缓存友好。

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.

在这里(除纹)我的建议是:考虑用标准容器(A 的std ::矢量&lt;的std ::矢量&lt; T&GT;&GT; 在这种情况下),这已经成型,测试,也使您的生活更轻松从原始指针和手动内存管理移动你而去。

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维数组,该版本是更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆