In .NET, which loop runs faster, 'for' or 'foreach'?

前端 未结 30 1350
抹茶落季
抹茶落季 2020-11-22 04:25

In C#/VB.NET/.NET, which loop runs faster, for or foreach?

Ever since I read that a for loop works faster than a foreach

30条回答
  •  别跟我提以往
    2020-11-22 04:39

    I wouldn't expect anyone to find a "huge" performance difference between the two.

    I guess the answer depends on the whether the collection you are trying to access has a faster indexer access implementation or a faster IEnumerator access implementation. Since IEnumerator often uses the indexer and just holds a copy of the current index position, I would expect enumerator access to be at least as slow or slower than direct index access, but not by much.

    Of course this answer doesn't account for any optimizations the compiler may implement.

提交回复
热议问题