Basic dynamic array question. Use of new versus no new.

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jun 11 08:42:23 PDT 2014


On Tue, 10 Jun 2014 23:28:16 -0400, Kapps <opantm2+spam at gmail.com> wrote:

> On Wednesday, 11 June 2014 at 02:30:01 UTC, WhatMeWorry wrote:
>> In Mr. Cehreli's book it says
>>
>> Additionally, the length of dynamic arrays can be changed by assigning  
>> a value to this property:
>>
>> int[] array; // initially empty
>> array.length = 5; // now has 5 elements
>>
>> while in Mr. Alexandrescu's book, it says
>>
>> To create a dynamic array, use a new expression (ยง 2.3.6.1 on page 51)  
>> as follows:
>>
>> int[] array = new int[20]; // Create an array of 20 integers
>>
>>
>> Could someone please compare and contrast the two syntaxes. I presume  
>> the "new" command places the 2nd array in heap memory.
>
> They both do the same, create an array of n integers on the heap and set  
> the length to n. You can also use .capacity instead of .length to  
> allocate n but not adjust length.

This is slightly incorrect. Here is the difference as I see it:

1. Setting length goes through the extra steps of checking the current  
length, looking up the existing block (obviously with initial value of  
null, there isn't one), and allocating if necessary. A lot more code is  
executed.
2. The 'new' call will ALWAYS allocate a new block, even if array  
previously had data in it.
3. The block size allocated is not always n, it could be more.
4. You meant 'reserve', not 'capacity'. capacity checks how many elements  
the block can support.

Which way is easier/better? If you know you are starting with a blank  
array, then new is the way to go. This avoids any unnecessary extra checks  
for existing data.

The second way is required if you may already have some data in the array  
(i.e. prior to setting the length, arr.length != 0).

Also, I would recommend to use:

auto array = new int[20]

To avoid repeating the type.

-Steve


More information about the Digitalmars-d-learn mailing list