I’m working on a game for the xbox360, using XNA. On the Xbox the garbage collector performs rather badly compared to the one on a PC, so keeping garbage generated to a minimum is vital for a smoothly performing game.
I remember reading once that calling a delegate creates garbage, but now for the life of me can’t find any references to delegates creating garbage. Did I just make this up or are delegates messy?
If delegates are messy, bonus points for suggesting a workaround.
public delegate T GetValue<T>(T value, T[] args);
public static T Transaction<T>(GetValue<T> calculate, ref T value, params T[] args) where T : class
{
T newValue = calculate(value, args);
return foo(newValue);
}
My code looks vaguely like that at the moment, the only solution I can think of to rid myself of delegates is to pass in a class which inherits an interface IValueCalculator, and then I can call the method on that interface, that’s not really very neat though!
A delegate is itself an object, so if you create a delegate, perhaps for an anonymous method, and give this to some other method to execute, and don’t store the delegate for future reference, then yes, that will produce garbage.
For instance, this:
In this case, a new delegate object is created, but beyond the call to
ForEachit is not referenced, and thus eligible for garbage collection.However, calling delegates does by itself not produce garbage, any more so than calling any other method of the same type would. For instance, if you call a delegate that takes an
Objectparameter, passing in anInt32value, this value will be boxed, but that would happen if you called a normal method the same way as well.So using delegates should be fine, but excessive creation of delegate objects will be a problem.
Edit: A good article on memory management for Xbox and XNA is here: Managed Code Performance on Xbox 360 for XNA: Part 2 – GC and Tools. Pay attention to this quote:
As you can see, try to avoid creating lots of unnecessary objects, and you should fare better.