Array start index
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Tue Feb 7 14:43:20 PST 2017
On 02/07/2017 02:04 PM, Bastiaan Veelo wrote:
>> This optimization cannot work if the array is a static array inside
>> the same struct. It would work with a dynamic array but then it would
>> probably be slower than applying the *(ptr+index) technique.
>
> You mean slower than the _payload[index - first] technique? Is that
> because of heap memory versus stack memory?
Mandatory disclaimer: We can't be sure without testing.
Not exactly because stack versus heap because the whole object might be
sitting in heap memory anyway:
alias S = StaticArray!(/* ... */);
S[] objects;
objects ~= S(/* ... */);
So, all of those are on the heap.
It's more about having everything at hand, near each other, close in
memory. If the member is a static array, then when we have an S[], all
members are there to be operated on. If the array in dynamic, then an
S[] has indirections, reaching out to the heap, which may involve
long-latency memory reads.
foreach (s; objects) {
s[42]; // May have a cache miss and read from memory
}
In the static array case, the entire body of s is already on the cache.
On the other hand, when the objects are large, then few of those can fit
in the cache. etc. One needs to profile to see what works better.
> Am I correct that the reason that a dynamic array would work is because
> it is allocated independently from the struct, meaning that its address
> stays the same even if the struct is moved?
Yes, that would be a requirement to prevent the self-reference.
> We could .reserve a dynamic
> array in initialize() to prevent it being resized.
Makes sense.
Another solution that came to my mind: You can keep the self-referencing
solution but make sure that the objects are not moved after initialize():
S[] objects;
objects.reserve(100);
objects.each!(o => o.initialize());
// The objects will not move if you're careful
> Thanks again.
> Bastiaan.
Ali
More information about the Digitalmars-d-learn
mailing list