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

主宰稳场 提交于 2019-12-30 04:34:25

问题


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);
}

回答1:


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.




回答2:


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.




回答3:


Binary serialization is very fast I use it a lot for this kind of problem

Deep cloning objects




回答4:


If you are copying the properties during run time, reflection would be the answer. I would go for serialization if its not during run time. Serialization vs Reflection look at this once.




回答5:


void Copy(object copyToObject, object copyFromObject)
{
    BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;

    FieldInfo[] fields = copyFromObject.GetType().GetFields(flags);
    for (int i = 0; i < fields.Length; ++i)
    {
        BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
            | BindingFlags.Static;
        FieldInfo field = copyFromObject.GetType().GetField(fields[i].Name, bindFlags);
        FieldInfo toField = copyToObject.GetType().GetField(fields[i].Name, bindFlags);
        if(field != null)
        {
            toField.SetValue(copyToObject, field.GetValue(copyFromObject));
        }
    }
}


来源:https://stackoverflow.com/questions/8181484/copy-object-properties-reflection-or-serialization-which-is-faster

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!