On 07-Oct-12 12:10, Jakob Ovrum wrote:
On Sunday, 7 October 2012 at 07:36:08 UTC, Philippe Sigaud wrote:
On Sat, Oct 6, 2012 at 8:32 PM, Dmitry Olshansky
<[email protected]> wrote:
Your current code may have some bad impact on performance:
return "(" ~ to!string(res.numerator) ~ "/" ~
to!string(res.denominator) ~
")";
Allocates 4 times. ~ operator is convenient shortcut to get job done but
it's unsuitable for building strings and formatted output.
And the solution is?
Appender and formattedWrite can do this with a minimal amount of memory
allocations.
The best solution is of course the writeTo function from DIP9 [1], which
hasn't been accepted yet for some reason.
[1] http://www.prowiki.org/wiki4d/wiki.cgi?LanguageDevel/DIPs/DIP9
Ehem.. I've been pushing for DIP9 a lot of time. But then I find out
that it is already here (and been for some time).
Like I said use a special overload of toString that is exactly writeTo.
Just define method with this signature:
void toString(scope void delegate(const(char)[]) sink)
And bingo! It's used in all of formatting stuff like write(f)(ln),
format, formattedWrite etc.
e.g. before posting I played with this:
import std.stdio, std.format;
struct A{
int k;
void toString(scope void delegate(const(char)[]) sink)
{
formattedWrite(sink, "[%d]", k);
}
}
void main(){
A a = A(90);
writeln(a);
}
--
Dmitry Olshansky