Is there a fast way to copy a generic TList?
Copy.Capacity := List.Count;
for Item in List do
Copy.Add (Item);
is very slow. There seems to be no way to use CopyMemory
since I can't get the memory adress of the internal array (which is obvious from an information hiding viewpoint). I miss something like
List.Copy (Copy);
which uses the knowledge of the internal representation to improve performance. Can it be done?
To clone a list, one can iterate through the original list and use the clone method to copy all the list elements and use the add method to append them to the list. Approach: Create a cloneable class, which has the clone method overridden. Create a list of the class objects from an array using the asList method.
To clone a list just call . ToList(). This creates a shallow copy.
Use the AddRange() method to append a second list to an existing list. list1. AddRange(list2);
The MemberwiseClone method creates a shallow copy by creating a new object, and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed.
For the generic TList<T>
it is simply not possible to implement the function you want. That's because copy the contents of T
may involve more than a simple memory copy. If T
contains any managed types (i.e. strings, interfaces etc.) then the reference counts on those managed objects must be incremented.
T
does contain managed types then I doubt that you can do much better then the code you already have.T
does not contain any managed types then a memory copy is viable but you will need to create your own class to encapsulate this list since TList<T>
is not appropriate.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