- Home /
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.
Answer by whydoidoit · Sep 29, 2012 at 12:27 PM
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.
Thanks. I will try to replace Invoke with a more direct call.
Well - I ended up caching the action ins$$anonymous$$d of invoking on each frame. So the reflection overhead happens only on first call to an unknown function, but later it is cached as an Action. Thanks, accepted.
EDIT: But by the way, I do not see any significant performance. Some improvement, yes, but nothing major - at least not within the editor. $$anonymous$$aybe on other systems it will be more meaningful.
".. and never Send$$anonymous$$essage.." You know a somewhat related problem that gripes me. A collider (on a Rock, say) bashes you, you have to get some info from the script attached to the Rock, so you have to ................. GetComponent. Arrrg! All these GetComponents every time there's a little scoring to do. That annoys the hell out of me and I've never seen a way around it.
@Fattie - I agree. When I started with Unity this confused me a lot. I always tried to call OtherObject.Some$$anonymous$$ethodInAttachedScript() banging my head against the table trying to figure out why its not working. I also try to avoid these ugly GetComponent where I can.
Answer by WhendricSo · Nov 11, 2018 at 08:51 PM
SendMessage is only about four times slower than using a delegate. In most cases, the performance penalty is negligible.