Allowing iteration without generating any garbage

前端 未结 7 1199
时光取名叫无心
时光取名叫无心 2021-02-01 04:49

I have the following code in an object pool that implements the IEnumerable interface.

public IEnumerable ActiveNodes
{
    get
    {
        for (int i         


        
7条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-01 05:13

    You could implement your own IEnumerator class which will enumerate over these active nodes.

    Now if you can guarantee that only one client will be enumerating over the active nodes at any one time, your class can cache this class so only a single instance exists. Then no garbage will need collecting. The call to ActiveNodes will call reset to start enumerating from the start.

    This is a dangerous assumption to make, but if you are optimising you may be able to consider it

    If you have multiple clients enumerating over these nodes at any time, then each will need its own instance of IEnumerator to be able to store their current cursor position in the collection. In which case these will need to be created and collected with each call - and you may as well stick with your original design.

提交回复
热议问题