1

I have an object in c# that needs co be copied many times and fast.

Currently I'm doing this with

public static void CopyFieldsInto<T>(T from, T to,bool ommitNulls=false) where T : new()
{
     foreach (var f in GetAllFieldsByType<T>())
     {
          var v = f.GetValue(from);
          if (ommitNulls&&v==null)
          {
              continue;
          }
          f.SetValue(to, v);
     }
}

The problem is that GetValue and SetValue take too long and slow it down.

Is there a better way to do this?

hcerim
  • 959
  • 1
  • 11
  • 27
Arsen Zahray
  • 24,367
  • 48
  • 131
  • 224
  • 1
    Do you control the source code of the object? You could implement an interface that helps with this and then you wouldn't need to use reflection. If you have to be able to do this for arbitrary objects, reflection is your only choice. – xxbbcc May 16 '17 at 14:54
  • I'm considering doing exactly this. However, going through each of the fields manually is time consuming and may cause issues later on, when I add additional fields and forget to mention them in the clone method – Arsen Zahray May 16 '17 at 14:57
  • 3
    Have a look at http://stackoverflow.com/questions/5476575/clone-with-better-performance – MakePeaceGreatAgain May 16 '17 at 14:57
  • 1
    @ArsenZahray Hand-coding the clone field-by-field is by far the fastest option (in terms of performance). – xxbbcc May 16 '17 at 15:00
  • `XmlSerializer` actually generates and compiles code for each type. Also I don't know how `FormatterServices.PopulateObjectMembers()` performs, it might be worth at try. – C.Evenhuis May 16 '17 at 15:05

1 Answers1

1

If you need to use reflection to copy the properties of the object, then there is no way to avoid using GetValue and SetValue. Here is another similar approach to yours. Also might be worth considering using AutoMapper or a tool like it.

Community
  • 1
  • 1
Yaakov Ellis
  • 40,752
  • 27
  • 129
  • 174
  • 1
    "no way to avoid using GetValue and SetValue"? No one forces you to do so - you can emit code (source, IL or expression trees) to do so just fine - http://stackoverflow.com/questions/321650/how-do-i-set-a-field-value-in-an-c-sharp-expression-tree – Alexei Levenkov May 16 '17 at 15:19