Hello,
I was wondering if allocating all members of a structure contiguously helps the CPU to reduce number of fetches from main memory / disk.
Example:
struct MyStruct
{
void* data;
void* data1;
};
void initMyStruct(MyStruct** ms)
{
size_t requiredSize = sizeof(MyStruct);
requiredSize += sizeOfData;
requiredSize += sizeOfData1;
BYTE* mem = allocator(requiredSize);
*ms = (MyStruct*)mem;
(*ms)→data = *ms + 1;
(*ms)→data1 = mem + sizeof(MyStruct) + sizeOfData;
}
Does the code above have any benefit over allocating MyStruct::data and MyStruct::data1 separately? Like will it reduce number of accesses to main memory?
As far as I remember, data gets loaded into cache in chunks based on the line size. So only a part of MyStruct::data may get loaded if we assume sizeOfData greater than the line size. So we will need another trip to main memory to load the remaining parts of MyStruct::data and MyStruct::data1. Assuming all this is correct, is there any advantage in allocating struct members contiguously with the struct?
Thank you