开发者

fastest multi-type array solution?

开发者 https://www.devze.com 2023-03-16 21:34 出处:网络
I need high-performance iteration over transient arrays (on stack and/or in heap) which can store mixed types of data, including various types of pointers.

I need high-performance iteration over transient arrays (on stack and/or in heap) which can store mixed types of data, including various types of pointers.

I thou开发者_如何学JAVAght of using unions to determine largest size of several supported array members.

is the following, the fastest (safe) architecture and solution?

union array_sizer {
    void *(* funcPtr)();
    void *dataPtr;
    struct {int i} *strPtr;
    int intVal;
    float floatVal;
}

// create an array of 10 item *pairs*.
union array_sizer *myArray = malloc(22 * sizeof(union array_sizer));

// fill up the (null-terminated) array 

// then, knowing that every *even* item is an int...
for(int i=0; myArray[i].intVal; i+=2){
    //(... do something in loop ...)
}

the array data will be created from functions which enforce data integrity, so the for loop can be pretty skimpy on error checking beyond null-termination.


I would make a parallel 'look up table' which indexes into the original array to say what type it is. So make an enum representing the types and make that a corresponding array.

However if you look at performance if you do it this way you will get page faulting and cache misses because likely the 2 arrays are going to be on different pages. So to get round this what you want to do is instead of a 'struct of arrays' make an 'array of structs'. To do this create a struct which has 2 members : the enum type constant and the data itself. If you do this, when we fetch an index it will ensure the data and the corresponding type information will be on the same page.

This would be my preferred method from a high level design point of view.

0

精彩评论

暂无评论...
验证码 换一张
取 消