When appending to dynamic arrays the GC profiler reports as many
allocations when using .reserve and when not, although the real number
of allocations is lower:
$ nl -b a test.d
1 void main()
2 {
3 import std.stdio;
4
5 int[] arr;
6 arr.reserve(50);
7 writefln("capacity: %s", arr.capacity);
8
9 immutable limit = 100;
10 foreach (i ; 0 .. limit)
11 {
12 if(append(arr, i))
13 writefln("reallocation occurred: %s", i);
14 }
15 }
16
17 bool append(ref int[] arr, int value)
18 {
19 auto before = arr.ptr;
20 arr ~= value;
21 return arr.ptr !is before;
22 }
$ dmd -profile=gc -run test.d ; cat profilegc.log
capacity: 63
reallocation occurred: 63
bytes allocated, allocations, type, function, file:line
400 100 int[] test.append test.d:20
We can note that 100 allocations on line 20 are reported although only
one reallocation really happens.
When commenting line 6 (arr.reserve(50)) we get the following output:
$ dmd -profile=gc -run test.d ; cat profilegc.log
capacity: 0
reallocation occurred: 0
reallocation occurred: 3
reallocation occurred: 7
reallocation occurred: 15
reallocation occurred: 31
reallocation occurred: 63
bytes allocated, allocations, type, function, file:line
400 100 int[] test.append test.d:20
As many allocations exactly are reported by the GC profiler, and on
the same appending line. As far as I can tell arr.reserve does its
preallocation job but the GC is still reporting allocations that do
not appear.
Comment #1 by cpicard — 2016-07-14T12:45:52Z
I should mention that this was done with DMD32 2.071.1 on GNU/Linux
Comment #2 by razvan.nitu1305 — 2022-11-09T15:24:48Z
I am getting:
capacity: 63
reallocation occurred: 63
reallocation occurred: 91
bytes allocated, allocations, type, function, file:line
880 2 int[] test.append test.d:20
So it seems that this issue has been fixed.