What should I use for concat string into array in loop?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Tue Feb 13 02:10:39 UTC 2018


On Tuesday, February 13, 2018 01:58:42 Marc via Digitalmars-d-learn wrote:
> appender doesn't support string[] so in such case:
> > string[] output;
> > for(...) {
> >
> >    if(...) {
> >
> >      output ~= str;
> >
> >     }
> >
> > }
>
> Looking for avoid as many immediate allocations as possible, what
> should I use?

Well, the space allocation for dynamic arrays works the same way that it
does with something like vector in C++ or ArrayList in Java. So, it's
amortized constant cost. So, using ~= is just fine.

That being said, every time that ~= is called, the runtime has to check
whether there's room to append in place or whether it has to reallocate the
array. In most cases, if you're appending in a loop, there's going to be
room, but the check isn't necessarily as cheap as would be nice. So, as an
alternative, there's std.array.Appender/appender, which does some of the
checks itself instead of calling the runtime, which speeds it up. So, you
may want to use Appender, but ~= is going to work just fine.

There's also the reserve function for reserving a minimum capacity for the
array, so if you know roughly how much you're going to need, you can call
reserve to tell it to allocate at least that much capacity up front and
reduce the number of allocations - even eliminate them if you really do know
the required capacity up front, since if the capacity is large enough, the
call to reserve will have allocated the necessary memory, and none of the
append calls will actually end up allocating.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list