What is the simplest way of doing @nogc string concatenation?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Nov 3 12:10:33 PDT 2016


On Thursday, November 03, 2016 18:54:14 Gary Willoughby via Digitalmars-d-
learn wrote:
> What is the simplest way of doing @nogc string concatenation?

std.range.chain is the closest that you're going to get with actual strings.
Dynamic arrays require the GC to do concatenation, because they have to
allocate a new string. Now, you can do stuff like

char[] mallocConcat(const(char)[] lhs, const(char)[] right)
{
    immutable len = lhs.length + right.length;
    return (cast(char*)malloc(len))[0 .. len];
}

But then you have to worry about keeping track of that memory allocation
somehow so that you free it appropriately later. Similarly, if you're
dealing with some sort of maximum string size, you could have static array
somewhere that you assign to and slice, but then you have to have somewhere
appropriate for that static array to live - which is simple enough if you're
just going to operate on it and then let it go away but is much harder if
you actually want to pass the slice around like a normal string.

Really, if you want to be doing actual string concatenation without the GC
and have it be sane, you need a string type which handles its own memory -
presumably using malloc. Concenation with dynamic arrays really needs the
GC - particularly in light of the fact that dynamic arrays are not reference
counted.

In general though, I'd suggest trying to use chain and operating on ranges
rather than creating an actual string to operate on. And if you want to
avoid the whole auto-decoding thing in the process, you can combine it with
std.utf.byCodeUnit.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list