指针数组与元素的数组 [英] Array of pointers vs. array of elements

查看:102
本文介绍了指针数组与元素的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天早上我有一个关于这个话题的同事的讨论。他说,这总是最好分配数组作为指针数组,因为分配的每一个元素分别有更好的机会获得免费的内存块。 Somethink是这样的:

This morning I've had a discussion with a colleague about this topic. He says that it's always better to allocate arrays as arrays of pointers, since allocating every single element separately has better chances to get a free memory chunk. Somethink like this:

// Consider n_elements as a dynamic value
int n_elements = 10, i;
int **ary = (int **) malloc(sizeof(int *) * n_elements);

for(i = 0; i < n_elements; i++)
{
  ary[i] = (int *) malloc(sizeof(int));
}

相对于他的做法,我认为这是更好地分配元素的数组,只是因为你会得到一个紧凑的内存块,而不是一堆周围堆引用小号$ P $垫。事情是这样的:

As opposed to his approach, I think that is better to allocate arrays of elements, just because you'll get a compact memory chunk and not a bunch of references spread around the heap. Something like this:

int n_elements = 10;
int *ary = (int *) malloc(sizeof(int) * n_elements);

ary[0] = 100;

这次谈话我一直在想这件事,我最后的结论后,它所依赖。我觉得第二个解决方案更好的办法有小的数据类型为解决我上面提到的原因的时候,却大分配结构的数组时,可能是更好的第一个。

After this conversation I've been thinking about it, and my final conclusion is that it depends. I find the second solution a better approach when dealing with small datatypes for the reason I mentioned above, but when allocating arrays of large structs is probably better the first one.

除了我的结论,你怎么想呢?

Apart of my conclusion, what do you think about it?

推荐答案

他是错的任何主流的硬件我能想到的。 (至少在一般)。它可能会有一些变化,并有可能会出现一些特殊情况。当你可以选择在指针数组元素的数组。

He is wrong for any mainstream hardware I can think of. (at least in general). It could vary a little and there could be some special cases. Choose array of elements over array of pointers when you can.

CPU缓存像数据被连续包装。单独分配每个元素会增加高速缓存未命中,慢分配时间,浪费内存(由于分配对齐)。 CPU速度和内存之间的差距每年增长,增加连续打包数据和批量操作的好处。

CPU caches like data to be contiguously packed. Allocating each element separately will increase cache misses, slow allocation time, and waste memory (due to allocation alignment). The gap between CPU speeds and memory grows every year, increasing the benefits of contiguously packed data and batch operations.

您应该阅读这个问题,<一个被描述的文档href=\"http://stackoverflow.com/questions/8126311/what-every-programmer-should-know-about-memory\">What每个程序员应该知道内存。它描述了所有的插件和现代CPU的出局/详细记忆的关系,为什么连续数据是非常重要的。

You should read the document described in this question What Every Programmer Should Know About Memory. It describes all the ins and outs of modern CPU/Memory relationship in detail and why contiguous data is very important.

这篇关于指针数组与元素的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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