www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Dtnamic array memory allocation

reply Rob Adelberg <adelmetz mindspring.com> writes:
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;
  }
}
Jan 07 2010
next sibling parent Strtr <strtr spam.com> writes:
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;
   }
 }
Jan 07 2010
prev sibling next sibling parent bearophile <bearophileHUGS lycos.com> writes:
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
Jan 08 2010
prev sibling parent "Steven Schveighoffer" <schveiguy yahoo.com> writes:
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
Jan 08 2010