When invoking a method in C# using reflection, there seems to be an issue where a MethodInfo.invoke call will allocate ~32 bytes of memory, but only if the method being invoked has no parameters.This can lead to a huge amount of memory being allocated.
Example:
MethodInfo zeroParamMethod = target.GetType ().GetMethod ("ZeroParam");
MethodInfo oneParamMethod = target.GetType ().GetMethod ("OneParam");
object[] arguments = new object[] { 3 };
// Results in 30MB of allocated memory
// Same result when passing an empty object[] variable instead of null
for (int i = 0; i < 1000000; i++)
zeroParamMethod.Invoke (target, null);
// All good, no allocations
for (int i = 0; i < 1000000; i++)
oneParamMethod.Invoke (target, arguments);
public void ZeroParam () {}
public void OneParam (int _arg0) {}
The culprit appears to be a MonoMethodInfo.GetParametersInfo() call.
Is there any simple way to get around these extra allocations?
As a workaround, I could probably just create a delegate from the MethodInfo for this specific case (no parameters), but I'm still stumped as to why there aren't any allocations when the method being called does have parameters.
This code is running in the Unity3D game engine which I believe uses Mono 2.6.5
Aucun commentaire:
Enregistrer un commentaire