Passing dynamic arrays
Bruno Medeiros
brunodomedeiros+spam at com.gmail
Fri Nov 26 10:22:46 PST 2010
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?)
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.
The only advantage of the current behavior is that it is more noob
friendly, which is an advantage of debatable value.
--
Bruno Medeiros - Software Engineer
More information about the Digitalmars-d
mailing list