0%

Structure of Array in C++

What is array of structure

這就是我們一般常用的模式

1
2
3
4
struct Obj {
int a, b;
};
std::array<Obj, 100> objs;

What is structure of array

剛好和上面的觀念相反,將object的member集中在一起,以上面的例子來說,可以寫成這樣

1
std::tuple<std::array<int, 100>, std::array<int, 100>> objs;

Why structure of array

從上面兩個寫法看來,array of structure更為自然,容易咧解
那為什麼會有structure of array的出現,一切都是為了性能
例如這樣子的Code

1
2
3
int sum = 0;
for (auto v : objs)
sum += v.a;

由於CPU locality特性,a的stride是sizeof(Obj)大小,所以CPU Cache幾乎沒有作用
但如果寫成這樣

1
2
3
4
int sum = 0;
auto &as = std::get<0>(objs);
for (auto v : as)
sum += v;

由於std::array<int, 100>是個連續的memory area,因此在CPU locality方面比起上面方案好
不過有一好沒兩好
structure of array的缺點有

  • 程式碼不容易讀

How to use struct of array in C++

由於C++沒有原生的SOA支援,有第三方的Library供使用

不過C++ Refelction何時落地啊