Why is List.Enumerator faster than my implementation?

前端 未结 1 862
轮回少年
轮回少年 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<T>:

    public DynamicArrayEnumerator<T> GetEnumerator()
    {
        return new DynamicArrayEnumerator<T>(this);
    }
    
    IEnumerator<T> IEnumerable<T>.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<T> without any boxing, and without virtual dispatch. This is exactly what List<T> 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)
提交回复
热议问题