Usage of memory by arrays

Jonathan M Davis newsgroup.d at jmdavisprog.com
Thu Apr 5 22:06:10 UTC 2018


On Thursday, April 05, 2018 21:44:35 unDEFER via Digitalmars-d wrote:
> OK, without reallocation:
>
> ====================8<====================
> void main()
> {
>      float[3] f;
>      float[3][] x;
>      writefln("float = %s bytes", float.sizeof);
>      writefln("float[3] = %s bytes", f.sizeof);
>
>      int before = MemoryUsage();
>
>      int total = 100;
>      x = new float[3][total*1000];
>
>      int after = MemoryUsage();
>      writefln("%dK * float[3] = %d Kbytes", total, (after-before));
> }
> ====================>8====================
>
> $ ./memory
> float = 4 bytes
> float[3] = 12 bytes
> 100K * float[3] = 2300 Kbytes
>
> Why this so?

You could also look at how x.capacity compares to x.length as well as
core.memory.GC.stats() to see what the GC thinks that it's using. On my
system, the x.capacity was only 9 greater than x.length, and GC.stats
printed as

Stats(1200128, 598016)

whereas 100,000 * 12 is 1,200,000, meaning that the GC claims to only be
using 128 more bytes than the dynamic array itself. Since FreeBSD doesn't
have the same /proc as Linux, I can't test using your MemoryUsage function,
so I don't know what it would claim, but if that's giving the entire memory
of the program, then the extra memory could be used by something in the C
runtime. Either way, I'd suggest looking at the result of GC.stats to see
what the GC thinks it's using on your system, which should give you a clue
as to what's using the memory. And at minimum, x.capacity will tell you how
much is used specifically for the buffer that the dynamic array is a slice
of.

- Jonathan M Davis



More information about the Digitalmars-d mailing list