Better way to append to array than ~= ?

Jordan Wilson wilsonjord at gmail.com
Wed Apr 4 21:54:30 UTC 2018


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?

I believe you are right to question the ~= in regards to 
performance. So, what I would do is replace this loop:

foreach(c; to!string(arg))
{
     bar ~= MySpecialType(c);
}

with this one liner:
bar ~= arg.map!(a => MySpecialType(a.to!char)).array;

To my mind, you replace multiple appends with just the one append 
(to be fair, I don't know what the .array is doing internally, 
but I'm sure whatever it does is nice and optimised).

Jordan



More information about the Digitalmars-d-learn mailing list