Why is List.Enumerator faster than my implementation?

前端 未结 1 863
轮回少年
轮回少年 2021-02-05 12:20

I\'ve found myself in a position where I have to roll my own dynamic array implementation, due to various large performance benefits (in my case). However, after creating an enu

1条回答
  •  长发绾君心
    2021-02-05 12:33

    Okay, aside from benchmarking problems, here's how you can make your DynamicArray class more like List:

    public DynamicArrayEnumerator GetEnumerator()
    {
        return new DynamicArrayEnumerator(this);
    }
    
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
    
    IEnumerator IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
    

    Now, code which knows it's working with a dynamic array can iterate with a DynamicArrayEnumerator without any boxing, and without virtual dispatch. This is exactly what List does. The compiler notices when a type implements the pattern in a custom manner, and will use the types involved instead of the interfaces.

    With your current code, you're getting no benefit from creating a struct - because you're boxing it in GetEnumerator().

    Try the above change and fix the benchmark to work for longer. I'd expect to see a big difference.

    0 讨论(0)
提交回复
热议问题