Performance Comparison between for, foreach, and ForEeach() method
BenchmarkDotNet v0.14.0, Windows 11 (10.0.22631.3958/23H2/2023Update/SunValley3)
AMD Ryzen 7 5800H with Radeon Graphics, 1 CPU, 16 logical and 8 physical cores
.NET SDK 8.0.304
[Host] : .NET 8.0.8 (8.0.824.36612), X64 RyuJIT AVX2
ShortRun-.NET 5.0 : .NET 5.0.17 (5.0.1722.21314), X64 RyuJIT AVX2
ShortRun-.NET 6.0 : .NET 6.0.32 (6.0.3224.31407), X64 RyuJIT AVX2
ShortRun-.NET 7.0 : .NET 7.0.20 (7.0.2024.26716), X64 RyuJIT AVX2
ShortRun-.NET 8.0 : .NET 8.0.8 (8.0.824.36612), X64 RyuJIT AVX2
ShortRun-.NET Core 3.0 : .NET Core 3.0.3 (CoreCLR 4.700.20.6603, CoreFX 4.700.20.6701), X64 RyuJIT AVX2
ShortRun-.NET Core 3.1 : .NET Core 3.1.32 (CoreCLR 4.700.22.55902, CoreFX 4.700.22.56512), X64 RyuJIT AVX2
IterationCount=3 LaunchCount=1 WarmupCount=3
Comparison: Mean
Method | Categories | Length | .NET Core 3.0 | .NET Core 3.1 | .NET 5.0 | .NET 6.0 | .NET 7.0 | .NET 8.0 |
for |
Array |
1000 |
293.0 ns |
294.6 ns |
246.7 ns |
245.4 ns |
243.9 ns |
242.3 ns |
foreach |
Array |
1000 |
476.0 ns |
242.9 ns |
240.5 ns |
243.3 ns |
239.2 ns |
237.9 ns |
ForEach() |
Array |
1000 |
1,433.8 ns |
1,674.4 ns |
1,444.4 ns |
1,434.5 ns |
1,432.3 ns |
243.6 ns |
Method | Categories | Length | .NET Core 3.0 | .NET Core 3.1 | .NET 5.0 | .NET 6.0 | .NET 7.0 | .NET 8.0 |
for |
List |
1000 |
480.3 ns |
479.9 ns |
478.0 ns |
392.4 ns |
477.6 ns |
394.7 ns |
ForEach() |
List |
1000 |
1,562.5 ns |
1,737.7 ns |
1,684.6 ns |
1,675.2 ns |
1,572.6 ns |
619.3 ns |
foreach |
List |
1000 |
1,759.1 ns |
1,693.5 ns |
1,882.4 ns |
718.4 ns |
489.2 ns |
480.1 ns |