布局在结构的内存。阵列和在C / C结构的阵列结构++ [英] Layout in memory of a struct. struct of arrays and array of structs in C/C++

查看:176
本文介绍了布局在结构的内存。阵列和在C / C结构的阵列结构++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C / C ++假设我定义一个名为一个简单的结构如下。

In C/C++ suppose I define a simple struct named point as follows.

struct test
{
double height;
int    age;
char   gender;
}

有关这个结构的特定实例说测试A A.height,A.age,A.gender 连续
在记忆中?

For a specific instance of this struct say test A are A.height, A.age, A.gender contiguous in memory?

更普遍,如何在内存中的布局阵列的结构和结构的数组是什么样子?一张照片将是非常有益的。

More generally, how do the layouts in memory for a Structure of Arrays and an Array of structures look like? A picture would be really helpful.

推荐答案

他们不一定会在内存中连续的。这是由于结构填充

They will not necessarily be contiguous in memory. This is due to struct padding.

然而,在特定的情况下,它很可能是连续的。但是,如果你改变了,以这样的:

However, in your particular case, it may very well be contiguous. But if you changed the order to something like this:

struct test
{
    char   gender;
    int    age;
    double height;
}

那么他们极有可能会无法进行。然而,在特定情况下,你仍可能性别后得到填充,以重新调整结构为8个字节。

then they most likely will not be. However, in your particular case, you will still likely get padding after gender, to realign the struct to 8 bytes.

SOA之间的差异(阵列结构体)和AOS(结构的数组)会是这样的:

The difference between SoA (Struct of Arrays) and AoS (Array of Structs) would be like this:

SOA:

-----------------------------------------------------------------------------------
| double | double | double | *pad* | int | int | int | *pad* | char | char | char |
-----------------------------------------------------------------------------------

AOS:

-----------------------------------------------------------------------------------
| double | int | char | *pad* | double | int | char | *pad* | double | int | char |
-----------------------------------------------------------------------------------

注意,每个结构中是AOS垫。尽管SOA在阵列之间垫。

Note that AoS pads within each struct. While SoA pads between the arrays.

这有以下权衡:


  1. AOS 更趋于可读性程序员,因为每个对象,保持在一起。

  2. AOS 可能有更好的缓存局域如果结构的所有成员一起访问。

  3. SOA 可能是因为分组相同的数据类型一起更有效,有时暴露出矢量化。

  4. 在许多情况下, SOA 使用较少的内存,因为填充是唯一的阵列之间,而不是每一个结构之间。

  1. AoS tends to be more readable to the programmer as each "object" is kept together.
  2. AoS may have better cache locality if all the members of the struct are accessed together.
  3. SoA could potentially be more efficient since grouping same datatypes together sometimes exposes vectorization.
  4. In many cases SoA uses less memory because padding is only between arrays rather than between every struct.

这篇关于布局在结构的内存。阵列和在C / C结构的阵列结构++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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