On Tuesday, 3 April 2018 at 19:02:25 UTC, Vladimirs Nordholm
wrote:
Hello people.
I currently have a function which multiple times per second
takes in arguments, and appends the argument as my special
type. The following code should explain what I do more properly:
struct MySpecialType { char c; }
auto foo(Args...)(Args args)
{
MySpecialType[] bar;
foreach(ref arg; args)
{
static if(is(typeof(arg) == MySpecialType))
{
bar ~= arg;
}
else
{
foreach(c; to!string(arg))
{
bar ~= MySpecialType(c);
}
}
}
// do more stuff
}
Now, from my trace.log, some of the topmost things on the
timing list are `std.array.Appender!(immutable(char).<more
stuff>`. I also remember reading some years ago that ~= isn't
optimal for speed.
So my question is: Is there a better and/or faster way of doing
this, or is this the best approach?
In this specific case, since you know the length of `Args`, you
can pre-allocate an array of that size and loop through it doing
your initialization.
However, if you want really performant code, you should allocate
a static array on the stack outside of the function and pass it
in as a buffer.