View mode: basic / threaded / horizontal-split · Log in · Help
January 08, 2010
Dtnamic array memory allocation
Does the dynamic array pre-allocate any memory?

I'm curious if the ~= on an array would be time sensitive. Would it make sense
to allocate memory myself and then reset the length?

class A
{
uint [] array;
:
 this()
 {
    array = new uint [10];
    array.length = 0;
 }
}
January 08, 2010
Re: Dtnamic array memory allocation
Rob Adelberg Wrote:

> Does the dynamic array pre-allocate any memory?
> 
> I'm curious if the ~= on an array would be time sensitive. Would it make sense
> to allocate memory myself and then reset the length?
> 
> class A
> {
> uint [] array;
> :
>   this()
>   {
>      array = new uint [10];

or, "array.length = 10;"  ?

>      array.length = 0;
>   }
> }
January 08, 2010
Re: Dtnamic array memory allocation
Rob Adelberg Wrote:
> Does the dynamic array pre-allocate any memory?

It doesn't preallocate, and currently array appending in D is a slow or very slow operation.
If you need to speed it up, you can use a struct that performs this operation in a faster way, that's available in D2 in the Phobos, and in D1 can be found around (I have a version too for D1). Something like an Appender or ArrayBuilder.

Bye,
bearophile
January 08, 2010
Re: Dtnamic array memory allocation
On Thu, 07 Jan 2010 23:32:21 -0500, Rob Adelberg <adelmetz@mindspring.com>  
wrote:

> Does the dynamic array pre-allocate any memory?

No.  It allocates on request.  Appending does pre-allocate more memory  
then asked, the logic being if you are repeatedly appending, you want to  
optimize the allocations.

>
> I'm curious if the ~= on an array would be time sensitive. Would it make  
> sense
> to allocate memory myself and then reset the length?

If by time sensitive, you mean it is a performance killer?  It is to some  
degree :)  There is a patch in the works for D2 that will make it more  
efficient, but if you require the best efficiency, I'd suggest using an  
array builder object like bearophile alluded to.  That way, your appends  
don't need to look up GC info.

>
> class A
> {
> uint [] array;
> :
>   this()
>   {
>      array = new uint [10];
>      array.length = 0;
>   }
> }


This is a common trick, but after the patch it will be incorrect on D2  
(the syntax will compile, but your preallocation will be wasted).  There  
will be a new function to replace this.

-Steve
Top | Discussion index | About this forum | D home