Are GetField and GetProperty slow? (C# Reflection)

Updated on November 29, 2016 in [A] C# .Net
Share on Facebook0Tweet about this on TwitterShare on Google+0Share on Reddit0
4 on November 29, 2016

I was just working on some project, and I got a scenario where the best solution to the problem I can think of was reflection.

It’s a part of a plugin I am making in Unity. There is a class I don’t want the user to mess around with, they should only use it to get references to instances I make for that class. There are a few members in the class that are not supposed to be accessible by the user. So I made them private and used reflection to get them.

There is just one problem… I have heard reflection can be pretty slow. That it’s good to use it from things that are called from time to time, but the way I used it here is inside of a for loop (not a nested one, but still a loop), that’s inside of a function I expect the user to call pretty often (sometimes even every Update).

I found many people that talked about it online, but I am now asking specifically about GetField and GetProperty methods. Are they slow?

  • Liked by
3 on November 29, 2016

Indeed, reflection is slow.
The question is whether it’s too slow.
Only one way to find that out… 😉

on November 29, 2016

You mean just testing it, right?

I don’t think such a thing can affect much on a 12 thread CPU (at 4.35GHz). I guess I could slowly disable threads and underclock it… Well yeah, I think I will do it. But not at this level of development, I think it’s something I should worry about later.

I think I will just call that method on the Update method both with the version that uses reflection and the other one, slowly underclocking my CPU and disabling threads (until I get to an amount that shows me the performance difference), looking at which one it burns more (hopefully I won’t fry my CPU 😛 ).
Do you have any other ideas for how I can test it?

on November 29, 2016

In windows you can also set the affinity (thread count) for each process via the task manager. That should help. You can see the results in the profiler.

on November 29, 2016

I had no idea you can do that. :O

The reason I was actually lazy to do it now is because I though I will have to go into the bios and disable them there… But if you can do it in windows I don’t have to be lazy! 😀

Show more replies
  • Liked by