页面

分类

Arrays of Structures/Objects

2016/10/19, by wingfire ; 分类: 计算机技术, 程序设计; 0 comments

An interesting programming paradigm.

类似于数据库中的按列存储。库LibFlatArray

    Arrays of Structures is the normal programming model.

    Let's take a toy example, say I'm looking at some census data and have a structure that looks like:

    struct citizen_t {
        string first_name;
        string last_name;
        int salary;
        int age;
    };

    Then the Array of Structures container would be:
    vector<citizen_t> aos_citizens;

    The Structure of Arrays version of the same data would look like:

    struct soa_citizens_t {
        vector<string> first_names;
        vector<string> last_names;
        vector<int> salary;
        vector<int> age;
    };

    soa_citizens_t soa_citizens;


    Why does this matter?

    Let's say I want to calculate the average salary of 300 million citizens. 
    The code is a simple iterative average and very simple.

    // Array of Structures
    int avg = 0;
    int t = 1;
    for ( auto & c : aos_citizens ) {
        avg += (c.salary - avg) / t;
        ++t;
    }


    // Structures of Arrays
    int avg = 0;
    int t = 1;
    for ( int salary : soa_citizens.salary ) {
        avg += (salary  - avg) / t;
        ++t;
    }

    Run this under a simple benchmark:
    https://ideone.com/QNqKpD

    AoS 3.03523 seconds
    SoA 1.94902 seconds


    Both loops are doing the exact same work but the memory layout allows the second loop to run much faster.

Array-of-Structs: Array-of-Structs Struct-of-Arrays: Struct-of-Arrays

添加评论:

 
 the email would not displayed
 

您可以使用 Markdown 语法。

您必须启用浏览器的 JavaScript 功能才能发表评论。