Re: Dyn Arrays



"Alex Moore" <alex.moore@xxxxxxxxxxx> schreef in bericht
news:MY9fi.17626$wH4.16440@xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Can I use SetLength to redimension a dynamic array.
For Instance can I do somthing like:

for I:= 1 to N do
begin
SetLength(MyArray, I);
Do Something with MyArray[I - 1];
end;

I am told that this leaks memory. Is that correct?


Yes, you can. And it will not leak memory.
If you resize to a smaller size, information at the end is lost. If you
resize to a larger size, the new elements will be undefined (in most cases,
see Help).

When increasing, new memory will be allocated, the old data will be copied
and the old memory will be released.
When decreasing, the same will happen when the array has a reference count
bigger than 1. If the array is not shared the decrease will act on the
memory already allocated to the array, which is faster.

About your example:
- the range is 0..length(array)-1 so MyArray[i-1] will be OK
- "Do something" must start with an assignment to the array element, since
it will be undefined
- when N is large, this will be a time consuming algorithm

Tom


.



Relevant Pages

  • Re: Fast string operations
    ... Looping: I thought looping over arrays in managed code was "slow" ... array handling and such. ... The problem with TrimHelper is that it always returns a new string instance. ... The customer perceives this as a memory leak. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: High Memory Consumption of Classes and Arrays
    ... Only the array itself has overhead. ... memory as a reference type. ... > least consume 40 bytes of memory. ...
    (microsoft.public.dotnet.framework.performance)
  • Re: Fast linked list
    ... > amounts of memory rather than huge chunks of it. ... random insertions into a vector/dynamic array are not as slow ... to cause a cache miss. ... some hard numbers on speed differences between lists and arrays. ...
    (microsoft.public.vc.mfc)
  • Re: Fast linked list
    ... > amounts of memory rather than huge chunks of it. ... random insertions into a vector/dynamic array are not as slow ... to cause a cache miss. ... some hard numbers on speed differences between lists and arrays. ...
    (microsoft.public.vc.language)
  • Re: not enough storage... error using GetRows
    ... > array only contained ~150,000 rows. ... It took 19 minutes for GetRows to return (db ... and the prog had consumed 200MB of memory. ... The first one allocates some 180MB, the next two only allocate about 47MB ...
    (microsoft.public.vb.database.ado)