Passing dynamic arrays

spir denis.spir at gmail.com
Fri Nov 26 11:37:02 PST 2010


On Fri, 26 Nov 2010 18:22:46 +0000
Bruno Medeiros <brunodomedeiros+spam at com.gmail> wrote:

> 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.

Well, except that "noobs" usually don't care about performance.
(Anybody would else preallocate, I guess, if only because it is just a few more key strokes; but the corresponding idiom is not that obvious:
	T[] xxx = new T[yyy.length];
)


Denis
-- -- -- -- -- -- --
vit esse estrany ☣

spir.wikidot.com



More information about the Digitalmars-d mailing list