Is it possible to invoke a MulticastDelegate
and process the return value of every attached handler without allocating any memory?
Background
In the scheme of normal things, the Delegate[]
allocated by MulticastDelegate.GetInvocationList()
is negligible. However in certain cases, it is important to minimise allocations. For example, during gameplay in Xbox games running on the compact framework, every 1MB allocated will trigger a collection and nasty framerate hitch.
After using CLR Profiler to hunt down and eliminate most allocations during gameplay, I'm left with 50% of the garbage being caused by Farseer Physics collision callback invocations. It needs to iterate the full invocation list since the user can return false
to cancel the collision response from any of the attached handlers (and invoking the delegate without using GetInvocationList()
simply returns the result of the last attached handler).
For reference, here is the Farseer code in question:
// Report the collision to both participants. Track which ones returned true so we can
// later call OnSeparation if the contact is disabled for a different reason.
if (FixtureA.OnCollision != null)
foreach (OnCollisionEventHandler handler in FixtureA.OnCollision.GetInvocationList())
enabledA = handler(FixtureA, FixtureB, this) && enabledA;