Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy object properties: reflection or serialization - which is faster?

I have two objects of the same type and need to copy property values from one object to another. There are two options:

  1. Use reflection, navigate through the properties of the first object and copy the values.

  2. 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);
}
like image 589
net_prog Avatar asked Nov 18 '11 11:11

net_prog


Video Answer


2 Answers

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, BinaryFormatter used 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. BinaryFormatter vs reflection in terms of performing shallow copy. Reflection code I used can be seen here:

var newPerson = Activator.CreateInstance<Person>();
var fields = newPerson.GetType().GetFields(BindingFlags.Public 
    | BindingFlags.Instance);
foreach (var field in fields)
{
    var value = field.GetValue(person);
    field.SetValue(newPerson, value);
}

What are the results compared to ObjectCopier class you're using? Reflection seems to perform 7 times faster than serialization code. This however applies to Person class with public fields. For properties, difference is still noticable, but it's only 2 times faster.

I assume difference comes from the fact that BinaryFormatter needs 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.

like image 158
k.m Avatar answered Sep 20 '22 13:09

k.m


Ultimately, general-purpose serializers (such as BinaryFormatter, via ObjectCopier) are using reflection. How well they use it depends on the specific serializer, but there is always extra overhead involved if you are serializing.

Since you only want a shallow copy, a tool like AutoMapper is the most appropriate tool here; again, it is using reflection (but I expect it is doing it "the right way", i.e. not via GetValue()/SetValue()), but it doesn't have the serialization costs.

In this scenario, serialization is overkill; AutoMapper is perfectly reasonable. If you wanted deep-clones, it gets trickier... serialization may start being tempting. I still probably wouldn't choose BinaryFormatter myself, but I'm very fussy about serialization ;p

It would of course be trivial to right some basic reflection that does the same via GetValue() etc, but that would be slow. Another interesting option here is that you can use the Expression API to create an object copier at runtime.... but... AutoMapper does everything you'd need here, so it seems redundant effort.

like image 44
Marc Gravell Avatar answered Sep 22 '22 13:09

Marc Gravell