Passing dynamic arrays

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Fri Nov 26 11:16:50 PST 2010


On 11/26/10 12:22 PM, Bruno Medeiros wrote:
> On 09/11/2010 01:43, Jonathan M Davis wrote:
>> On Monday, November 08, 2010 16:50:46 so wrote:
>>> D arrays very powerful but you first need to understand what is going
>>> on.
>>> You should check the book.
>>> An inconsistency is the copy of static arrays at assignment, but
>>> necessary
>>> one.
>>> One thing i don't like about D arrays is an undefined case in dynamic
>>> array reallocation.
>>
>> It's perfectly defined, just not knowable at compile time. You can
>> even check the
>> array's capacity if you want to try and figure out when it's going to
>> happen.
>>
>> And there's not really any reasonable alternative. What would have happen
>> instead? Make an array reallocate _every_ time that it's resized? That
>> would be
>> highly inefficient and could really degrade performance. Appending
>> becomes O(n)
>> instead of amortized O(1). If you're not altering the actual elements
>> of the
>> array, then the current implementation is great. If you _are_ altering
>> them,
>> then simply dup the array to guarantee that it's been reallocated.
>>
>> - Jonathan M Davis
>
> Making the array reallocate _every_ time that it's resized (to a greater
> length) is actually not that unreasonable. Would it be highly
> inneficient? Only if you write bad code. TDPL agrees with you, I quote:
>
> "
> One easy way out would be to always reallocate a upon appending to it
> [...]
> Although that behavior is easiest to implement, it
> has serious efficiency problems. For example, oftentimes arrays are
> iteratively grown in a loop:
>
> int[] a;
> foreach (i; 0 .. 100) {
> a ~= i;
> }
>
> "
>
> Hum, "oftentimes"? I wonder if such code is really that common (and what
> languages are we talking about here?)

It would be difficult to challenge the assumption that appends in a loop 
are common.

> But more importantly, there is a simple solution: don't write such code,
> don't use arrays like if they are lists, preallocate instead and then
> fill the array. So with this alternative behavior, you can still write
> efficient code, and nearly as easily.

I disagree. Often you don't know the length to preallocate (e.g. input 
is from a file etc). The fact that there's a convenient append operator 
only makes things more in favor of supporting such idioms. The technique 
(exponential capacity growth) is well known.

> The only advantage of the current behavior is that it is more noob
> friendly, which is an advantage of debatable value.

I don't think the current behavior favors noobs.


Andrei


More information about the Digitalmars-d mailing list