How to reuse the space of RAM of an array of strings?

Steven Schveighoffer schveiguy at gmail.com
Fri Dec 21 22:31:26 UTC 2018


On 12/21/18 3:41 PM, Giovanni Di Maria wrote:
> Hi. Can you help me please?
> I asked also to "General Group" but i haven't solved my problem.
> I have tried many experiments but without success.
> I have a dynamic array of strings:
> string[] vec;
> 
> After to have inserted dynamically 5_000_000 strings to array, for six 
> times, i measure the RAM with an utility (for example Wise Memory 
> Optimizer), deleting the array every time.
> 
> Every time I destroy the array, but the RAM is always less.
> In particular:
> 
> - at beginning the FREE RAM is 1564 MB;
> - after first loop the FREE RAM IS 1480 MB
> - after second loop the FREE RAM IS 1415 MB
> - after third loop the FREE RAM IS 1402 MB
> - after forth loop the FREE RAM IS 1338 MB
> - after fifth loop the FREE RAM IS 1280 MB
> - after sixth loop the FREE RAM IS 1200 MB
> - at end the FREE RAM returns to 1564 MB
> 
> I want to reuse the dynamic array.
> 
> This is the program:
> 
> import std.stdio;
> string[] vec;
> void main()
> {
>      alloca();
>      alloca();
>      alloca();
>      alloca();
>      alloca();
>      alloca();
> }
> 
> void alloca()

Note: alloca is a builtin intrinsic, so I wouldn't use that as a 
function name. Don't think it's affecting your program, but I wanted to 
point that out.

> {
>      vec.destroy;

This does NOT free the ram, it simply resets vec to null.

If you want to free the memory, use

GC.free(vec.ptr); vec = null;

>      writeln("Filling .....");
>      for (int i = 0; i < 5000000; i++)
>          vec ~= "1234567890ABCDEFGHIL123456";

Note, this allocates a lot of smaller arrays on its way up to the really 
big array. You are better off doing:

vec.reserve(5_000_000);

which will pre-allocate the capacity needed. This will make you only 
allocate once.

-Steve


More information about the Digitalmars-d-learn mailing list