IEnumerable garbage creation
I have the following code in an object pool that impl开发者_开发问答ements the IEnumerable interface.
public IEnumerable<T> ActiveNodes
{
get
{
for (int i = 0; i < _pool.Count; i++)
{
if (_pool[i].AvailableInPool)
{
yield return _pool[i];
}
}
}
}
None of the elements in _pool will ever be collected, as the purpose of the pool is to keep references to all of them to prevent garbage creation.
Does anything in this code generate garbage?
(Perhaps C# creates an IEnumerable object that later will be collected?)
Does anything in this code generate garbage?
Yes, yield return
creates a temp IEnumerable<T>
.
C# generates an IEnumerable object which will need to be collected, and that enumerable object will create some enumerator objects which will also need to be collected. If you want to follow the IEnumerable pattern though it is difficult to avoid those.
精彩评论