This is a theoretical question intended to generate a look-up list of pros and cons of different data storage ways in Delphi.
Let's say we have a record:
type
TMyRecord = record
X,Y,Z: Single;
IsValid: Boolean;
end;
Basic options of storing an array of such records are:
array of TMyRecord;
TList
with getter/setterTList<TMyRecord>;
I'm specifically interested about #1 vs #3 comparison, how much is the difference between those, especially performance-wise.
So the question is what are the pros and cons of TArray<T> usage instead of Array of MyType? Show activity on this post. The main advantage is less onerous type identity rules. Consider: These two variables are not assignment compatible. It is a compiler error to write: then these two variables are assignment compatible.
Largest disadvantage is performance on some operations like insert, depending on how you implement the dynamic array. The most common implementation is to have internally an array plus an initial capacity, and handle the array growth operation transparently.
It's fine if all code is in your control, but when using code from a variety of sources, the advent of generic dynamic arrays makes a huge difference. The other advantage that springs to mind, in similar vein, is that you can readily use the generic array type as the return type of a generic method.
2D Array is used to represent matrices. For any reason a user wishes to store multiple values of similar type then the Array can be used and utilized efficiently. Now let’s see some disadvantages of the array and how to overcome it: Array size is fixed: The array is static, which means its size is always fixed.
TList<T>
pros:
TList<T>
cons:
TList<T>[i]
actually returns a copy of its element. So you can't write something like TList<TMyRec>[idx].SomeField := foo
. Instead, you have to use temporary variable. Array obviously allows such expression.
David Heffernan mentioned TList<T>.List
which eliminates this drawback; however, it appeared only in XE3
For myself I wrote TRecordList<T>
class which operates items as pointers (like classic TList does).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With