memory management of array

Bill Baxter wbaxter at gmail.com
Sat Dec 20 03:48:42 PST 2008


On Sat, Dec 20, 2008 at 8:22 PM, Michel Fortin
<michel.fortin at michelf.com> wrote:
> On 2008-12-19 17:01:48 -0500, "Bill Baxter" <wbaxter at gmail.com> said:
>
>> In addition to what other people have said, if you know the length the
>> array will be eventually you can preallocate by doing this:
>>
>> float[] arr;
>> arr.length = N;
>> arr.length = 0;
>
> The downside of reserving this way is that it'll initialize all the array
> elements you're reserving with a default value for no reason at all. I think
> reserve should be part of the language so we can avoid this.

+1,  reserve() should be in the language.

Also, the spec isn't exactly clear that the above will always work.
All I can find is this:
"""
To maximize efficiency, the runtime always tries to resize the array
in place to avoid extra copying. It will always do a copy if the new
size is larger and the array was not allocated via the new operator or
a previous resize operation.
"""

It says the runtime "tries", but the doesn't really give any explicit
guarantees about what will happen when the new length is shorter.  So
I think from this language a spec-conforming D compiler would be free
to release the memory when you set length to 0 if it wanted to.

--bb



More information about the Digitalmars-d mailing list