c++ - Make 2 non-static fields (that are dynamic arrays) use memory near each other -


let b1 , b2 dynamic-size storage classes.
(e.g. b1~std::vector<char> b2~std::vector<float>)

in c++11, if code b1 , b2's move , copy function (rule of five), class c contains them fields copy/move correctly default automatically.

class c{     b1 b1; b2 b2; }; 

it works good.

problem

today, got profile result + did test performance issue.
main objective: have make b1 , b2 of same instance of c allocate memory near each other :-

b1[0]  b1[1] ... b1[b1.size-1] (minimum gap) b2[0]  b2[1] ... b2[b2.size-1]  

if can, performance boost 10-20% whole program.

my poor solution

i can use custom allocator (pseudo-code):-

class c{     b1 b1;      b2 b2;     allocator* allo_; // can heap allocator      public: void reserve(int size){         //old : b1.reserve(size); b2.reserve(size);  .... easy         //new :-         b1 b1next; b2 b2next;         int nb1=b1next.howmuchiwant(size);          int nb2=b2next.howmuchiwant(size);         //^ request amount of bytes needed if capacity="size"         void* vptr=allo_->allocate(nb1+nb2);         b1next.setmemory(vptr);         b2next.setmemory(vptr + nb1);  //add "vptr" "nb1" bytes         b1next=b1;   //copy assignment (not move memory)         b2next=b2;   //copy assignment (not move memory)         b1=std::move(b1next);   //move memory         b2=std::move(b2next);   //move memory          //clean previous "vptr" (not shown)     } }; 

it works, code become far harder debug/maintain. not mention c's move , copy.

in old version, copy/move mess appear in b1 , b2.
now, mess appears in every class use data-structure b1 , b2 directly.

question

what c++ technique/design-pattern/idiom can help?
answer, no runable code required. pseudo code or concept enough.

i regret not providing mcve.
custom allocator , array management things hard minimizing.

one possibility improve data locality going struct of vectors vector of structs. instead of

struct s {     std::vector<char> c;     std::vector<int> i; }; s data; 

use a

struct s {     char c;     int i; }; std::vector<s> data; 

that way, data stored , don't need tinker around custom allocators. whether applicable in situation depends on 2 conditions:

  • is necessary have char (or int) contiguous? e.g. because api called regularly requires vector of respective type.
  • is number of stored char , int equal (at least equal)?

Comments

Popular posts from this blog

Sort a complex associative array in PHP -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -