Think of a dynamic array as being a lower level construct than TStringList
or TList<T>
.
The dynamic array offers direct access to elements via a pointer. The language hides the pointer from you, but that's essentially all a dynamic array is. But you are in charge of any reallocations and if you wish to insert or remove items, then you have to write the code, and deal with the details.
The higher level collection classes, TStringList
and TList<T>
are built on top of dynamic arrays. That is internally how the contents are stored. But the collection classes wrap that up for you. Higher level operations like inserting and deleting, and many more, are provided as methods. In essence, these collection classes provide a great deal more convenience than raw dynamic arrays.
To illustrate, consider the act of inserting an item. For a dynamic array you would do this:
- Resize the array.
- Move items that are after the insertion point from position i to i+1.
- Assign the inserted item.
If you need to write this code more than once, well, you are doing it wrong.
For the high level collection you write:
List.Insert(Index, Value);
and let the class take care of the details.
Note that for historical reasons, and because strings are especially important, developers tend to use the bespoke, dedicated TStringList
class rather than TList<string>
. Again the dedicated class offers functionality above and beyond TList<string>
because it specialises in strings and can offer functionality that is bespoke to strings. Again, the dedicated class offers convenience.
One place where dynamic arrays come in handy is when you don't want to incur the boilerplate of lifetime management. So for the desktop compilers that don't have ARC for classes, you need to explicitly destroy TList<T>
instances. But dynamic arrays have lifetime managed by ARC. If you are synthesising arrays in one shot, and then not resizing them, then the lifetime management issue can make arrays more convenient to use.
As a rule of thumb, prefer the high level collection classes. They should be your default choice. Sometimes dynamic arrays are the right choice, but that tends to be for more specialised scenarios.