Need for speed
Ali Çehreli
acehreli at yahoo.com
Thu Apr 1 20:17:15 UTC 2021
On 4/1/21 12:55 PM, H. S. Teoh wrote:
> - Constructing large arrays by appending 1 element at a time with `~`.
> Obviously, this requires many array reallocations and the associated
> copying
And that may not be a contributing factor. :) The following program sees
just 15 allocations and 1722 element copies for 1 million appending
operations:
import std.stdio;
void main() {
int[] arr;
auto place = arr.ptr;
size_t relocated = 0;
size_t copied = 0;
foreach (i; 0 .. 1_000_000) {
arr ~= i;
if (arr.ptr != place) {
++relocated;
copied += arr.length - 1;
place = arr.ptr;
}
}
writeln("relocated: ", relocated);
writeln("copied : ", copied);
}
This is because the GC does not allocate if there are unused pages right
after the array. (However, increasing the element count to 10 million
increases allocations slightly to 18 but element copies jump to 8 million.)
Ali
More information about the Digitalmars-d-learn
mailing list