Usage of memory by arrays

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu Apr 5 21:49:52 UTC 2018


On Thursday, April 05, 2018 21:27:54 unDEFER via Digitalmars-d wrote:
> On Thursday, 5 April 2018 at 21:11:53 UTC, Steven Schveighoffer
>
> wrote:
> > But the old block doesn't go away! It's collected and stored in
> > a free list for future allocations.
> >
> > -Steve
>
> Big thanks, -Steve! Really program like the next:
>
> ==============8<==============
> void main()
> {
>      float[3] f;
>      float[3][] x;
>      float[3][] y;
>      writefln("float = %s bytes", float.sizeof);
>      writefln("float[3] = %s bytes", f.sizeof);
>
>      int total = 200;
>      foreach(i; 0..total)
>      {
>          foreach (j; 0..1000)
>          {
>              x ~= [0.01, 0.02, 0.03];
>          }
>      }
>
>      int before = MemoryUsage();
>      foreach(i; 0..total/2)
>      {
>          foreach (j; 0..1000)
>          {
>              y ~= [0.01, 0.02, 0.03];
>          }
>      }
>      int after = MemoryUsage();
>      writefln("%dK * float[3] = %d Kbytes", total/2,
> (after-before));
> }
> ==============>8==============
>
> Prints:
> float = 4 bytes
> float[3] = 12 bytes
> 100K * float[3] = 1320 Kbytes
>
> Very well. I'm thinking how to optimize my game program to not be
> "pathological" on loading the models.

If you know the size of the arrays beforehand, then either call reserve on
the array before you start appending, in which case, the capacity of the
array will be roughly the actual length. Alternatively, you can just
allocate the dynamic array to the correct length and then assign each
element. I don't know which would result in less memory being used (since
they're both likely to have some extra capacity depending on the exact
number and size of the elements), but they both should roughly take up the
amount of memory required, and you'll only get one heap allocation, meaning
that you won't be creating any extra garbage in the process.

- Jonathan M Davis



More information about the Digitalmars-d mailing list