I have two objects of the same type and need to copy property values from one object to another. There are two options:
-
Use reflection, navigate through the properties of the first object and copy the values.
-
Serialize the first object and deserialize a copy.
Both work for my requirement, the question is which do I better use in the terms of speed (cost)?
Example
class Person
{
public int ID { get; set; }
public string Firsthand { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public decimal Weight { get; set; }
}
Need to copy property values from Person p1 to Person p2.
For this simple sample – which method is faster?
Update
For serialization I use the ObjectCopier suggested here: Deep cloning objects
For reflection I use this code:
foreach (PropertyInfo sourcePropertyInfo in copyFromObject.GetType().GetProperties())
{
PropertyInfo destPropertyInfo = copyToObject.GetType().GetProperty(sourcePropertyInfo.Name);
destPropertyInfo.SetValue(
copyToObject,
sourcePropertyInfo.GetValue(copyFromObject, null),
null);
}
It all depends on what you want to copy, and what kind of serializer you plan to use. Thing with serializers is, some of them might be actually using reflection as underlying mechanism of building objects.
Edit #1: As far as I know,
BinaryFormatterused by your class does utilize reflection to do its work. So question is, can you write better (faster?) custom reflection code for your types than Microsoft did for general scenario?Edit #2: Out of curiosity, I’ve run simple test.
BinaryFormattervs reflection in terms of performing shallow copy. Reflection code I used can be seen here:What are the results compared to
ObjectCopierclass you’re using? Reflection seems to perform 7 times faster than serialization code. This however applies toPersonclass with public fields. For properties, difference is still noticable, but it’s only 2 times faster.I assume difference comes from the fact that
BinaryFormatterneeds to use streams, which introduce additional overhead. Yet this is just my assumption, which might be far from facts.Source code for testing program I used can be found here. Anybody is welcome to point flaws and possible problems with it 🙂
Sidenote
As with all “I was wondering…” benchmarks, I suggest you take it with a grain of salt. Such optimizations should be only made when their performance actually becomes an issue.