Sometimes 100 lines of code can fix your ctfe perf
Paul Backus
snarwin at gmail.com
Tue Aug 24 20:14:24 UTC 2021
On Tuesday, 24 August 2021 at 19:35:39 UTC, Alexandru Ermicioi
wrote:
> On Tuesday, 24 August 2021 at 16:58:26 UTC, Adam D Ruppe wrote:
>> On Tuesday, 24 August 2021 at 16:52:30 UTC, Ali Çehreli wrote:
>>> I know it's not the same use case but I've standardized on
>>> the following style for string formatting both for CTFE and
>>> run time:
>>>
>>> auto s = format!"hello %s world %s"(a, b);
>>
>> yikes that's like the worst thing in the whole D world.
>> brutally slow by all metrics.
>
> Best here from use point of view is text method for simple use
> cases:
>
> text("Hello ", a, " world ", b);
>
> Hope it is better on perf at ctfe than format.
Looks like it'd be worse. Internally, `format` uses
`formattedWrite` with an `Appender` as the output range [1],
which means that (in the best case) it can write its result
directly into the output buffer without allocating any memory for
intermediate results. `text`, on the other hand, converts each of
its non-string arguments to a string separately *before* writing
them to its output buffer [2], so even in the best case it will
require O(arguments) additional allocations compared to `format`.
I am honestly kind of surprised that `text` works like
this--before looking, I'd have expected both to use the same
mechanism under the hood. Maybe it's necessary to avoid some
edge-case inconsistency between `value.to!string` and
`value.format!"%s"`?
[1]
https://phobos.dpldocs.info/source/std.format.write.d.html#L681
[2]
https://dpldocs.info/experimental-docs/source/std.conv.d.html#L4233
More information about the Digitalmars-d
mailing list