relative benefit of .reserve and .length

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon May 2 16:37:21 PDT 2016


On 5/2/16 5:57 PM, Eto Demerzel wrote:

> For example:
>
>      auto invalid_tokens = uninitializedArray!(string[])(result.failure);
>      invalid_tokens.length = 0;
>
>      foreach (index, ref token_result; result.results) {
>          if (token_result.error == "NotRegistered") {
>              invalid_tokens.assumeSafeAppend() ~= tokens[index];
>          }
>          else ...
>      }
>
>      // use invalid_tokens
>
> It would've been almost perfect code if `assumeSafeAppend` wasn't very
> costly. Now I need to declare separate length for `invalid_tokens`, so I
> can assign tokens by index. Which I don't like because arrays have
> `length` built into them.

Only call assumeSafeAppend when you *remove* data from the array end. 
When you call it on an array that is already appendable, it does 
nothing. Appendable means the array slice ends at the end of the actual 
data.

Better code:

invalid_tokens.length = 0;
invalid_tokens.assumeSafeAppend;

Without seeing your "else", I can't say where else it should be, if at all.

-Steve


More information about the Digitalmars-d-learn mailing list