Passing dynamic arrays

Bruno Medeiros brunodomedeiros+spam at com.gmail
Fri Nov 26 13:20:05 PST 2010


On 26/11/2010 19:36, Pelle Månsson wrote:
> On 11/26/2010 07:22 PM, Bruno Medeiros wrote:
>> 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.
>
> What about when you don't know the length before, or working with
> immutable elements?
>

I must recognize I made a huge blunder with that, my reasoning was 
indeed very wrong. :(


don't know the length:
Do the exponentional growth yourself. Double the array length when it 
gets full, and keep track of real length in a separate variable. At the 
end, downsize the array to real length.
- This version is significantly more complex than the code with the 
current behavior, significantly enough to counter my argument (the 
"nearly as easily" part).
- It's actually also slightly less efficient, because whenever you grow 
the array, half of the elements have to be default-initialized, which is 
not the case when you just grow the capacity (using current resize 
behavior). I think one might resolve this by doing some cast to void[]'s 
and back, but that would make this code version even more complex.

immutable:
preallocate another array _whose elements are typed as tail-immutable_, 
fill it, at the end cast it to the array typed with immutable elements.
- Ouch, this one is even worse, especially depending on what the type of 
the immutable elements are, because of the need to determine the 
tail-immutable version of that type.
If the elements are Objects, it's not even possible to do that, so you 
would need to type the temporary array as void*[]. And that would make 
the code even more complex if you'd want to access and use the elements 
while the array is being constructed. (alternatively you could cast away 
all the immutable from the element type, but it's less safe, on a more 
complex loop you would risk modifying them by mistake)
:/


-- 
Bruno Medeiros - Software Engineer


More information about the Digitalmars-d mailing list