In this article I’ll explain how to copy an object. I’ll explain the difference between shallow and deep copying, and then show multiple ways to do both approaches for copying objects. At the end, I’ll show a performance and feature comparison to help you decide which object copying method to use.
Table of Contents
Shallow copy vs Deep Copy
There are two types of copying: shallow copying and deep copying. Shallow copy creates a new object and copies primitive values and references to the new object. Deep copy creates a new object, copies primitive values, and recursively creates new referenced objects.
The following diagram illustrates the key difference between shallow and deep copy:
As illustrated above, when you shallow copy, the original NFLTeam object and copy point to the exact same HeadCoach object.
Because they are pointing to the same HeadCoach object, if you change original.HeadCoach.Name, it also changes copy.HeadCoach.Name. This may be undesirable. As long as you understand that shallow copying means your references are shared, then it’s OK. If this is not acceptable, you’ll need to use deep copy.
Whether you choose to do a shallow copy or deep copy will depend on your requirements. The important thing is to be aware of the difference between these two types of copying, and choosing the one that makes sense in your situation.
Example object to copy
I’ll use the following object to demonstrate the different copy methods. This is a sufficient choice for comparing different copy methods because it has references to other objects and has a list of objects.
var team = new NFLTeam()
{
City = "Detroit",
Name = "Lions",
Conference = Conferences.NFC,
Divison = Divisions.North,
HeadCoach = new Person()
{
FirstName = "Matt",
LastName = "Patricia"
},
Stats = new Stats()
{
RegularSeasonWins = 559,
RegularSeasonLosses = 658,
RegularSeasonTies = 32,
PlayoffWins = 7,
PlayoffLosses = 13,
SuperBowlWins = 0,
SuperBowlLosses = 0
},
Players = new List<Player>()
{
new Player()
{
FirstName = "Matthew",
LastName = "Stafford",
Position = PlayerPositions.QB,
YearsOfExperience = 12,
College = "Georgia"
},
new Player()
{
FirstName = "Kenny",
LastName = "Golladay",
Position = PlayerPositions.WR,
YearsOfExperience = 4,
College = "Northern Illinois"
},
new Player()
{
FirstName = "Tracy",
LastName = "Walker",
Position = PlayerPositions.DB,
YearsOfExperience = 3,
College = "Louisiana-Lafayette"
},
new Player()
{
FirstName = "T.J.",
LastName = "Hockenson",
Position = PlayerPositions.TE,
YearsOfExperience = 2,
College = "Iowa"
}
}
};
Code language: C# (cs)
How to shallow copy an object
Shallow Copy copies values and references. It’s extremely fast, but doesn’t deep copy reference types.
To shallow copy you can call MemberwiseClone() on the object. This is a protected method, so it can only be called from within an instance method. Here’s an example of using MemberwiseClone():
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Person ShallowCopy()
{
var person = (Person)MemberwiseClone();
return person;
}
}
Code language: C# (cs)
This creates a new Person object and copies the existing Person object’s properties (FirstName, LastName) to the new object.
Note: You can implement deep copying manually by 1) Using MemberwiseClone() to copy each value type and then 2) Deep copying reference types (by implementing MemberwiseClone() in every class that needs to be copied). This can be a little tedious to implement if you have deeply nested objects, but it’s blazing fast.
Calling MemberwiseClone() if you can’t modify the class
Luckily, there’s a sneaky way to call MemberwiseClone() from outside the class. You can use reflection to invoke MemberwiseClone(). This is especially useful if you’re trying to copy an object from third-party code – which you wouldn’t be able to modify yourself.
Here is the reflective ShallowCopy() method.
public class ObjectCopier
{
public object ShallowCopy(object o)
{
return o?.GetType().GetMethod("MemberwiseClone", BindingFlags.Instance | BindingFlags.NonPublic)?.Invoke(o, null);
}
}
Code language: C# (cs)
The following test calls ShallowCopy().
[TestMethod()]
public void ShallowCopyTest()
{
var team = GetTeam();
var objectCopier = new ObjectCopier();
var copy = (NFLTeam)objectCopier.ShallowCopy(team);
Assert.AreNotSame(team, copy);
Assert.AreSame(team.HeadCoach, copy.HeadCoach);
Assert.AreSame(team.Name, copy.Name);
Assert.AreEqual(team.Name, copy.Name);
}
Code language: C# (cs)
Notice the outcome:
- team.HeadCoach and copy.HeadCoach are pointing to the same object. This is because shallow copy doesn’t create new references.
- team.Name and copy.Name are pointing to the same string object. This is OK though, because strings are immutable, so it really doesn’t matter that they are pointing to the same string object.
How to deep copy an object
Deep copying creates a new object, copies values, and recursively creates new referenced objects, including strings.
There are three main ways to do this:
- Manually copying
- Serialization
- Walk the object graph using recursion + reflection. This is what the serializers do, so there is no point doing this yourself. This is out of scope for this article, since I wouldn’t recommend reinventing the wheel with this approach.
The method you choose depends on balancing maintainability, performance, and how general-purpose it needs to be. Furthermore, if you are trying to deep copy a third party object, then your options may be very restricted.
For our purposes here, we’ll define deep copy as copying the public properties of a class. If you need to copy private fields, you’ll need to stick to using the built-in BinaryFormatter approach.
Deep copy an object manually
The first option is to simply manually copy the object. This is simple and very fast. The downside is that any time you add a new property, you’ll need to remember to update the copy method.
Here’s the ManuallyCopy() method.
public class ObjectCopier
{
public NFLTeam ManuallyCopy(NFLTeam nflTeam)
{
return new NFLTeam
{
City = nflTeam.City,
Conference = nflTeam.Conference,
Divison = nflTeam.Divison,
Name = nflTeam.Name,
HeadCoach = new Person()
{
FirstName = nflTeam.HeadCoach.FirstName,
LastName = nflTeam.HeadCoach.LastName
},
Players = nflTeam.Players.Select(p => new Player()
{
College = p.College,
FirstName = p.FirstName,
LastName = p.LastName,
Position = p.Position,
YearsOfExperience = p.YearsOfExperience
}).ToList(),
Stats = new Stats()
{
PlayoffLosses = nflTeam.Stats.PlayoffLosses,
PlayoffWins = nflTeam.Stats.PlayoffWins,
RegularSeasonLosses = nflTeam.Stats.RegularSeasonLosses,
RegularSeasonTies = nflTeam.Stats.RegularSeasonTies,
RegularSeasonWins = nflTeam.Stats.RegularSeasonWins,
SuperBowlLosses = nflTeam.Stats.SuperBowlLosses,
SuperBowlWins = nflTeam.Stats.SuperBowlWins
}
};
}
}
Code language: C# (cs)
Here’s the test:
[TestMethod()]
public void ManualCopyTests()
{
var team = GetTeam();
var objectCopier = new ObjectCopier();
var copy = objectCopier.ManuallyCopy(team);
Assert.AreNotSame(team, copy);
Assert.AreNotSame(team.HeadCoach, copy.HeadCoach);
Assert.AreSame(team.Name, copy.Name);
Assert.AreEqual(team.Name, copy.Name);
}
Code language: C# (cs)
Two things to notice:
- team.HeadCoach and copy.HeadCoach are not the same, because it was deep copied.
- team.Name and copy.Name are the same string reference. Strings are immutable, so it doesn’t matter if they are shallow copied.
Deep copy an object with binary serialization using built-in BinaryFormatter
The next option is using the built-in BinaryFormatter to do binary serialization. To create a deep copy with binary serialization, you first serialize an object, then deserialize it. This is quite simple to do using the built-in BinaryFormatter class.
The only downside is you need to add the [Serializable] attribute to every object in the object graph.
[Serializable]
public class NFLTeam
Code language: C# (cs)
If you don’t add this attribute, then you’ll get the following exception:
System.Runtime.Serialization.SerializationException: Type ‘TypeName’ in Assembly ‘AssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null’ is not marked as serializable.
If you are in control of all the objects in the object graph, then you can simply add the [Serializable] attribute. However, if there is a third-party object in the object graph without the [Serializable] attribute, you’ll need to use a different approach.
Here’s the code:
public class ObjectCopier
{
private BinaryFormatter binaryFormatter;
public ObjectCopier()
{
binaryFormatter = new BinaryFormatter();
}
public object DeepCopyBinaryFormatter(object o)
{
using (var ms = new MemoryStream())
{
binaryFormatter.Serialize(ms, o);
ms.Position = 0;
return binaryFormatter.Deserialize(ms);
}
}
}
Code language: C# (cs)
Here’s the test:
[TestMethod()]
public void DeepCopyBinaryFormatterTest()
{
var team = GetTeam();
var objectCopier = new ObjectCopier();
var copy = (NFLTeam)objectCopier.DeepCopyBinaryFormatter(team);
Assert.AreNotSame(team, copy);
Assert.AreNotSame(team.HeadCoach, copy.HeadCoach);
Assert.AreNotSame(team.Name, copy.Name);
Assert.AreEqual(team.Name, copy.Name);
}
Code language: C# (cs)
Notice that team.HeadCoach and copy.HeadCopy are not the same object. Even team.Name and copy.Name are different string objects. Binary serialization creates entirely new object references, including strings.
Deep copy an object with binary serialization using GroBuf
If you want to do binary serialization, but can’t, or don’t want to add the [Serialization] attribute to everything in the object graph, then you can use GroBuf. This simply binary serializes all public properties in the object graph. Because you don’t need to add any attributes, this is a nice low-maintenance option.
First, install GroBuf using the nuget package console:
Install-Package GroBuf
Code language: PowerShell (powershell)
Here’s the code that uses the GroBuf serializer. Notice that this is creating the Serializer instance ahead of time. This is critical for performance.
public class ObjectCopier
{
private Serializer groBufSerializer;
public ObjectCopier()
{
groBufSerializer = new Serializer(new PropertiesExtractor(), options: GroBufOptions.WriteEmptyObjects);
}
public object DeepCopyGroBufBinary(object o)
{
byte[] data = groBufSerializer.Serialize(o.GetType(), o);
return groBufSerializer.Deserialize(o.GetType(), data);
}
}
Code language: C# (cs)
Here’s the test:
[TestMethod()]
public void DeepCopyGroBufBinaryTest()
{
var team = GetTeam();
var objectCopier = new ObjectCopier();
var copy = (NFLTeam)objectCopier.DeepCopyGroBufBinary(team);
Assert.AreNotSame(team, copy);
Assert.AreNotSame(team.HeadCoach, copy.HeadCoach);
Assert.AreNotSame(team.Name, copy.Name);
Assert.AreEqual(team.Name, copy.Name);
}
Code language: C# (cs)
Warning: GroBuf is very slow on initial use. Use the performance recommendations mentioned below.
Deep copy an object with JSON serialization using the built-in System.Text.Json
If you want a very low-maintenance deep copy option, then JSON serialization is for you. You don’t need to add attributes anywhere, and you can use the built-in System.Text.Json to serialize then object to JSON and then deserialize it to a new object (therefore creating a deep copy).
Here’s the code:
public class ObjectCopier
{
private JsonSerializerOptions jsonOptions;
public ObjectCopier()
{
jsonOptions = new JsonSerializerOptions();
jsonOptions.Converters.Add(new JsonStringEnumConverter());
}
public object DeepCopyJson(object o)
{
var json = JsonSerializer.Serialize(o, jsonOptions);
return JsonSerializer.Deserialize(json, o.GetType(), jsonOptions);
}
}
Code language: C# (cs)
Here’s the test:
[TestMethod()]
public void DeepCopyJsonTest()
{
var team = GetTeam();
var objectCopier = new ObjectCopier();
var copy = (NFLTeam)objectCopier.DeepCopyJson(team);
Assert.AreNotSame(team, copy);
Assert.AreNotSame(team.HeadCoach, copy.HeadCoach);
Assert.AreNotSame(team.Name, copy.Name);
Assert.AreEqual(team.Name, copy.Name);
}
Code language: C# (cs)
Warning: System.Text.Json is very slow during initial use. Use the performance recommendations mentioned below.
Performance recommendations – cache serializers and warm them up
To improve performance I recommend the following two things:
1 – Cache serializer objects
During startup, create the serializer objects and options and save them for later. For example, reusing JsonSerializerOptions leads to a nice performance boost. Here’s how you’d create and that:
private JsonSerializerOptions jsonOptions;
public ObjectCopier()
{
jsonOptions = new JsonSerializerOptions();
jsonOptions.Converters.Add(new JsonStringEnumConverter());
}
Code language: C# (cs)
If you create the serializer objects (or serialization options in this case) each time you serialize, then that adds significant overhead and practically eliminates performance benefits.
2 – Warm up the serializers on startup
Some serializers are relatively slow on their first use compared to subsequent uses.
There are two reasons:
- They use reflection. The first time you use reflection to get type info, it’s a cache miss. It caches the type info, so subsequent lookups are very fast.
- They build and use internal caches. If you use GroBuf or System.Text.Json, you’ll notice that the first use is incredibly slow. Then subsequent uses are fast. This indicates that they build and use an internal cache.
So if you’re going to use the serializer over and over, it makes sense to warm it up by using it during startup.
Performance comparison of the different object copying methods
I compared the performance of the different copy methods by copying an object 100 times and capturing the min, max, and average times.
Method | Min (ms) | Max (ms) | Avg (ms) |
ShallowCopy | 0.0017 | 0.0085 | 0.00206 |
DeepCopyBinaryFormatter | 0.1249 | 0.2953 | 0.15459 |
DeepCopyJson | 0.0375 | 0.2542 | 0.04968 |
ManuallyCopy | 0.0019 | 0.0117 | 0.00253 |
DeepCopyGroBufBinary | 0.0043 | 0.0277 | 0.00648 |
Note: The reflective methods are always slower the first time they are executed. This is because type metadata gotten from reflection is lazy loaded. So in order to have a fair comparison, I “warmed up” all of the methods, so the reflective methods would not incur the penalty of the initial cache miss.
Here is the code I used to compare the speeds.
[TestMethod()]
public void SpeedTest()
{
var team = GetTeam();
var objectCopier = new ObjectCopier();
Stopwatch sw = new Stopwatch();
//Warm up - so reflective methods don't get reflection penalty
objectCopier.ShallowCopy(team);
objectCopier.DeepCopyBinaryFormatter(team);
objectCopier.DeepCopyJson(team);
objectCopier.ManuallyCopy(team);
objectCopier.DeepCopyGroBufBinary(team);
Dictionary<string, List<double>> times = new Dictionary<string, List<double>>();
times.Add(nameof(objectCopier.ShallowCopy), new List<double>());
times.Add(nameof(objectCopier.DeepCopyBinaryFormatter), new List<double>());
times.Add(nameof(objectCopier.DeepCopyJson), new List<double>());
times.Add(nameof(objectCopier.ManuallyCopy), new List<double>());
times.Add(nameof(objectCopier.DeepCopyGroBufBinary), new List<double>());
for (int i = 0; i < 100; i++)
{
sw.Start();
objectCopier.ShallowCopy(team);
sw.Stop();
times[nameof(objectCopier.ShallowCopy)].Add(sw.Elapsed.TotalMilliseconds);
sw.Restart();
objectCopier.DeepCopyBinaryFormatter(team);
sw.Stop();
times[nameof(objectCopier.DeepCopyBinaryFormatter)].Add(sw.Elapsed.TotalMilliseconds);
sw.Restart();
objectCopier.DeepCopyJson(team);
sw.Stop();
times[nameof(objectCopier.DeepCopyJson)].Add(sw.Elapsed.TotalMilliseconds);
sw.Restart();
objectCopier.ManuallyCopy(team);
sw.Stop();
times[nameof(objectCopier.ManuallyCopy)].Add(sw.Elapsed.TotalMilliseconds);
sw.Restart();
objectCopier.DeepCopyGroBufBinary(team);
sw.Stop();
times[nameof(objectCopier.DeepCopyGroBufBinary)].Add(sw.Elapsed.TotalMilliseconds);
}
foreach(var kvp in times)
{
Console.WriteLine($"Method={kvp.Key} Min={kvp.Value.Min()} Max={kvp.Value.Max()} Avg={kvp.Value.Average()}");
}
}
Code language: C# (cs)
Feature and performance comparison table
The following table shows a comparison of all the features and performance discussed in this article.
Method | Shallow or Deep Copy? | Creates new strings? | Copies private fields? | General-purpose? | Built-in? | Relative speed of initial use | Average speed (ms) | Works on third-party objects | Relative coding effort |
MemberwiseClone() | Shallow | No | No | Yes | Yes | Medium | 0.00206 | Yes | Very little. Add a one-line utility method. |
Manual deep copy | Deep | No | No | No | Yes | Fast | 0.00253 | Yes | Very high. Have to implement the manual copying, then remember to update it whenever classes change. |
Binary serialization using BinaryFormatter | Deep | Yes | Yes | Yes | Yes | Medium | 0.15459 | Must have [Serializable] attribute | Pretty high. You have to add the serializer logic + add [Serializable] to all objects in the object graph. |
Binary serialization using GroBuf | Deep | Yes | No | Yes | No | Very slow | 0.00648 | Yes | Practically no effort if you don’t care about speed. Low effort relatively if you want great performance. You just need to initialize it during startup and make it available everywhere. (See Performance Recommendation section) |
JSON serialization using System.Text.Json | Deep | Yes | No | Yes | Yes | Slow | 0.04968 | Yes | Same as above. |
Which object copy method should I use?
If you’re having trouble deciding which object copy method to use, then ask yourself the questions in the decision tree below.