Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast copy of TList <T>?

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?

like image 740
jpfollenius Avatar asked Feb 28 '12 09:02

jpfollenius


People also ask

How do I clone a list?

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.

How do you copy a list in C sharp?

To clone a list just call . ToList(). This creates a shallow copy.

How do I assign one list to another in C#?

Use the AddRange() method to append a second list to an existing list. list1. AddRange(list2);

What is C# MemberwiseClone?

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.


1 Answers

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.

  • If your T does contain managed types then I doubt that you can do much better then the code you already have.
  • If your 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.
like image 104
David Heffernan Avatar answered Oct 08 '22 01:10

David Heffernan