Allowing iteration without generating any garbage

前端 未结 7 1204
时光取名叫无心
时光取名叫无心 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:15

    Since XNA for XBox also works over the Compact Framework (and I suspect that's what you're working on given the hints you've given(1)), we can trust the XNA devs to teach us exactly when foreach creates garbage.

    To quote the most relevant point (although the entire article's worth reading):

    When doing a foreach over a Collection an enumerator WILL be allocated.

    When doing a foreach over most other collections, including as arrays, lists, queues, linked lists, and others:

    • if the collections are used explicitly, an enumerator will NOT be allocated.
    • if they are cast to interfaces, an enumerator WILL be allocated.

    So, if _pool is a List, array or similar and can afford to, you can either return that type directly or cast the IEnumerable to the respective type to avoid garbage during the foreach.

    As some additional reading, Shawn Hargreaves can have some useful additional information.

    (1) 60 calls per second, Compact Framework, can't go down to native code, 1MB of allocation before a GC is triggered.

提交回复
热议问题