Do you use D's GC?
Steven Schveighoffer
schveiguy at gmail.com
Tue Aug 3 18:18:48 UTC 2021
On 8/3/21 1:53 PM, Ali Çehreli wrote:
> On 8/3/21 9:31 AM, H. S. Teoh wrote:
>
> > (1) Use it by default until it starts showing up as a bottleneck in your
> > profiler.
> >
> > (2) When it does show up as a bottleneck, [...]
>
> That's engineering! :)
>
> However, dmd's -profile=gc switch seems to have a bug reported by
> multiple people where one may get a segmentation fault (or was it
> -profile?). Even though I've seen it as well, it is not clear whether
> it's my own code causing errors in a destructor.
>
> > Overall, I think I got about 50-60% performance improvement just by
> > several small code changes to an essentially GC-centric codebase.
>
> Same here.
>
> One surprising pessimization which I have not mentioned publicly before
> was with assigning to the .length property of a buffer. Was it supposed
> to allocate? I had the following function:
>
> void ensureHasRoom(ref ubyte[] buffer, size_t length) {
> buffer.length = length;
> }
>
> My idea was I would blindly assign and even if the length was reduced,
> the *capacity* would not change and memory would *not* be allocated by a
> later assignment.
Let's rewrite this into appending to see why this doesn't work:
```d
buffer = new int[100]; // start with some data;
auto buffer2 = buffer; // keep a reference to it (to give us a reason to
keep the data)
buffer = buffer[0 .. 50]; // "shrink" the length
buffer ~= 10; // appending, will reallocate because otherwise we stomp
on buffer2
```
It's no different for length setting:
```d
buffer = new int[100];
auto buffer2 = buffer;
buffer.length = 50;
buffer.length = 51; // must reallocate
buffer[$-1] = 10;
```
In order for a length change to *not* reallocate, you have to call
`assumeSafeAppend` on that adjusted buffer, to let the runtime know that
we don't care about any existing data that might be referenced by others.
-Steve
More information about the Digitalmars-d
mailing list