i'm developing xbox 360 game xna. i'd really use c#'s yield return
construct in couple of places, seems create lot of garbage. have @ code:
class componentpool<t> t : drawablegamecomponent { list<t> preallocatedcomponents; public ienumerable<t> components { { foreach (t component in this.preallocatedcomponents) { // enabled changes during iteration on components // example, it's not uncommon bullet components // disabled during collision testing // sorry didn't make clear if (component.enabled) { yield return component; } } } } ...
i use these component pools everywhere - bullets, enemies, explosions; numerous , transient. need loop on contents, , i'm ever interested in components active (i.e., enabled == true
), hence behavior of components
property.
currently, i'm seeing as ~800k per second of additional garbage when using technique. avoidable? there way use yield return
?
edit: found this question broader issue of how iterate on resource pool without creating garbage. lot of commenters dismissive, apparently not understanding limitations of compact framework, this commenter more sympathetic , suggested creating iterator pool. that's solution i'm going use.
the implementation of iterators compiler indeed use class objects , use (with foreach, example) of iterator implemented yield return
indeed cause memory allocated. in scheme of things problem because either considerable work done while iterating or considerably more memory allocated doing other things while iterating.
in order memory allocated iterator become problem, application must data structure intensive , algorithms must operate on objects without allocating memory. think of game of life of similar. iteration overwhelms. , when iteration allocates memory tremendous amount of memory can allocated.
if application fits profile (and if) first rule should follow is:
- avoid iterators in inner loops when simpler iteration concept available
for example, if have array or list data structure, exposing indexer property , count property clients can use loop instead of using foreach iterator. "easy money" reduce gc , doesn't make code ugly or bloated, little less elegant.
the second principle should follow is:
- measure memory allocations see when , should use first rule
Comments
Post a Comment