Why is sformat and formattedWrite (appender) allocating GC mem here?
cc
cc at nevernet.com
Sat Aug 31 12:07:56 UTC 2019
And what, if anything, can I do to avoid it?
string[] arr = ["abcd", "efgh", "ijkl"];
char[4096] buf;
char[] res;
writeln(GC.stats);
res = sformat(buf, "%s", arr);
assert(res.ptr == buf.ptr);
writeln(res);
writeln(GC.stats);
res = sformat(buf, "%s", arr);
assert(res.ptr == buf.ptr);
writeln(res);
writeln(GC.stats);
// Results:
Stats(64, 1048512, 80)
["abcd", "efgh", "ijkl"]
Stats(272, 1048304, 272)
["abcd", "efgh", "ijkl"]
Stats(464, 1048112, 464)
I get similar behavior trying to use formattedWrite with an
appender:
string[] arr = ["abcd", "efgh", "ijkl"];
auto formatBuffer = appender!(char[])();
formatBuffer.reserve(4096);
formatBuffer.clear();
writeln(GC.stats);
formatBuffer.formattedWrite!"%s"(arr);
writeln(formatBuffer.data);
writeln(GC.stats);
formatBuffer.clear();
formatBuffer.formattedWrite!"%s"(arr);
writeln(formatBuffer.data);
writeln(GC.stats);
// Results:
Stats(12288, 5230592, 4208)
["abcd", "efgh", "ijkl"]
Stats(12432, 5230448, 4352)
["abcd", "efgh", "ijkl"]
Stats(12576, 5230304, 4496)
Same thing if I use a format string like "%(%s,%)" rather than
just "%s". I'm guessing it's allocating a string first to write
the contents of the array and then inserting that string into the
buffer I supplied. Is there no way to have it skip this step and
just write each element (plus the joining punctuation, etc)
directly into the buffer?
More information about the Digitalmars-d-learn
mailing list