Performance of Linq
I have three benchmarks:
They operatate on two 1 million elements Vector3 arrays. Why the second one is three times slower? And why Linq is so much slower compared to
[Benchmark]
public float AverageLengthBetweenPointsZipLinq()
{
return V1
.Zip(V2, Vector3.Distance)
.Average();
}
[Benchmark]
public float AverageLengthBetweenPointsZipSelectLinq()
{
return V1
.Zip(V2)
.Select(tupel => Vector3.Distance(tupel.First, tupel.Second))
.Average();
}
[Benchmark]
public float AverageLengthBetweenPointsIterative()
{
float sum = 0f;
for (int i = 0; i < V1.Length; i++)
{
sum += Vector3.Distance(V1[i], V2[i]);
}
return sum / V1.Length;
} [Benchmark]
public float AverageLengthBetweenPointsZipLinq()
{
return V1
.Zip(V2, Vector3.Distance)
.Average();
}
[Benchmark]
public float AverageLengthBetweenPointsZipSelectLinq()
{
return V1
.Zip(V2)
.Select(tupel => Vector3.Distance(tupel.First, tupel.Second))
.Average();
}
[Benchmark]
public float AverageLengthBetweenPointsIterative()
{
float sum = 0f;
for (int i = 0; i < V1.Length; i++)
{
sum += Vector3.Distance(V1[i], V2[i]);
}
return sum / V1.Length;
}They operatate on two 1 million elements Vector3 arrays. Why the second one is three times slower? And why Linq is so much slower compared to
forfor loop. I want to better understand Linq and performance related to it.| Method | Mean | Error | StdDev | Allocated |
|---------------------------------------- |----------:|----------:|----------:|----------:|
| AverageLengthBetweenPointsZipLinq | 8.817 ms | 0.0385 ms | 0.0360 ms | 160 B |
| AverageLengthBetweenPointsZipSelectLinq | 23.230 ms | 0.0616 ms | 0.0577 ms | 216 B |
| AverageLengthBetweenPointsIterative | 1.398 ms | 0.0251 ms | 0.0235 ms | - || Method | Mean | Error | StdDev | Allocated |
|---------------------------------------- |----------:|----------:|----------:|----------:|
| AverageLengthBetweenPointsZipLinq | 8.817 ms | 0.0385 ms | 0.0360 ms | 160 B |
| AverageLengthBetweenPointsZipSelectLinq | 23.230 ms | 0.0616 ms | 0.0577 ms | 216 B |
| AverageLengthBetweenPointsIterative | 1.398 ms | 0.0251 ms | 0.0235 ms | - |