C# Invoke vs. Unity SendMessage

Hello everybody,

I have a need in my code to call a method by string every frame.
Right now I am using C# Invoke, like this:

Type thisType = handler.GetType();
MethodInfo theMethod = thisType.GetMethod(funcname);
if( theMethod != null ) 
	theMethod.Invoke(handler, new object[]{});

Now, I know it has some performance penalty, but I am wondering if it is a significant one to try and solve.

I know I can improve performance by caching it to a delegate, but my main question here is this:

Considering this needs to be done every frame - what would be faster; C# Invoke or Unity SendMessage?

Thanks in advance.

Unity SendMessage is also using reflection - so it will be as slow as your Invoke code, if not slower if it does some other processing. However, hopefully Unity will cache the delegates for methods it’s called in some kind of O(1) storage. I wouldn’t trust that though and never SendMessage unless it is a rare event (when it’s damn handy along with Broadcast and SendUpwards).

You are much better off caching that in an Action (or Action<parameter1, … >) if you call every frame - now that is very fast.

When you don;t know ahead of time all of the delegates then you can use this code I wrote to cache the signatures if you are running on an AOT environment like iOS.

SendMessage is only about four times slower than using a delegate. In most cases, the performance penalty is negligible.