Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clone with better performance

Tags:

c#

I want to create deep copy method and I found 3 ways to execute it

1-deep copy with pass each property 1 by 1

2-using reflection

3-using serialization

please which of them is the best at performance wise

like image 825
Mohammed Thabet Avatar asked Mar 29 '11 17:03

Mohammed Thabet


People also ask

What is the difference between deep cloning and shallow cloning?

1. In Shallow copy, a copy of the original object is stored and only the reference address is finally copied. In Deep copy, the copy of the original object and the repetitive copies both are stored.

What is the most efficient way to deep clone an object in javascript?

According to the benchmark test, the fastest way to deep clone an object in javascript is to use lodash deep clone function since Object. assign supports only shallow copy.

Does the clone method do a shallow or a deep copy?

clone() is indeed a shallow copy. However, it's designed to throw a CloneNotSupportedException unless your object implements Cloneable . And when you implement Cloneable , you should override clone() to make it do a deep copy, by calling clone() on all fields that are themselves cloneable.

What is deep copy?

A deep copy of an object is a copy whose properties do not share the same references (point to the same underlying values) as those of the source object from which the copy was made.


2 Answers

The first option, manually deep copying your values, will be the most performant by far.

Reflection will introduce quite a bit of overhead, as it is (relatively) slow to access data.

Serialization is adding a huge cost, as it serializes the data into a temporary structure, then reverses the process to set. This is again, very slow.

The only advantage to option 2 or 3 is that its potentially easier to implement, and reusable across multiple types. The first option has to be hand-written per type, but is much faster (and more efficient in memory usage than option 3, as well).

like image 65
Reed Copsey Avatar answered Oct 18 '22 05:10

Reed Copsey


I made graph with comparison of the three methods plus an expression trees method.

enter image description here

For large number of objects is reflection 5x faster and manual code and expression trees are 20x faster than serialization. The best by performance are therefore manual code and expression trees.

Links to used cloning codes (2.-4. used as an extension method):

  1. Manual: Written manually, no link.
  2. Cloning by Serialization
  3. Cloning by Reflection
  4. Cloning by Expression Trees
like image 27
frakon Avatar answered Oct 18 '22 04:10

frakon