Appending one element to a dynamic array

前端 未结 8 2201
太阳男子
太阳男子 2020-12-05 05:16

This is a very frequent pattern throughout my code:

SetLength(SomeDynamicArray, Length(SomeDynamicArray)+1);
SomeDynamicArray[High(SomeDynamicArray)] := NewE         


        
相关标签:
8条回答
  • 2020-12-05 06:17

    That's an anti-pattern that results in memory fragmentation. Instead use Generics.Collections.TList<T> and call the Add method to add new items.

    There is no one liner to extend an array and add an item. You could create your own dynamic array wrapper using generics to do this should you so desire. Essentially that's what Generics.Collections.TList<T> is.

    0 讨论(0)
  • 2020-12-05 06:20
    MyList.Add(myobject);
    

    IMO Dynamic arrays should only be used when at compile time you don't know the exact size of the array but at run time you will know.

    If you need to continually manipulate your array size, you shouldn't be using an array but a TList or one of its descendants, as others have mentioned: TObjectList, TInterfaceList, TStringList.Objects[] can all be used (and abused) and there are some new ones as well, and TList for primitive types. TList used to be something of a pain before generics were introduced into Delphi - you had to work with pointers - but with generics: TList <T> it's very easy.

    Also, use the capacity property of any list you create - it will pre-allocate the given amount of memory so your code doesn't cause lots of memory to get juggled around every time you perform an operation on your list. (If you go beyond the capacity you allocated, memory manager will give you more memory at runtime- you wan't fail - see Delphi Help)

    0 讨论(0)
提交回复
热议问题