布局在结构的内存。阵列和在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.
这有以下权衡:
- AOS 更趋于可读性程序员,因为每个对象,保持在一起。
- AOS 可能有更好的缓存局域如果结构的所有成员一起访问。
- SOA 可能是因为分组相同的数据类型一起更有效,有时暴露出矢量化。
- 在许多情况下, SOA 使用较少的内存,因为填充是唯一的阵列之间,而不是每一个结构之间。
- AoS tends to be more readable to the programmer as each "object" is kept together.
- AoS may have better cache locality if all the members of the struct are accessed together.
- SoA could potentially be more efficient since grouping same datatypes together sometimes exposes vectorization.
- In many cases SoA uses less memory because padding is only between arrays rather than between every struct.