[Solved] Which is faster, for loop or LINQ


Neither. Using a loop has less overhead than LINQ, so that is a good start.

Use the < operator in the loop condition, that is the standard way of writing such a loop, so it’s more likely that the compiler will recognise it and optimise it properly.

Using Math.Pow to square a number is not effective. It’s somewhere in the ballpark of 100 times faster to multiply it by itself:

public double CalculateDistance(List<double> list1, List<double> list2) {
  double dist = 0;
  for (int i = 0; i < list1.Count; i++) {
    double n = list1[i] - list2[i];
    dist += n * n;
  }
  return dist;
}

Edit:

Using PLINQ you would get a better performance for large sets. Testing it on my computer I found that with less than 10000 items it’s not faster to use PLINQ. For lists with 10 million items, I got about 40% shorter execution time.

I also found that using a projection I got about 30% shorter execution time than using Zip:

public double CalculateDistance(List<double> list1, List<double> list2) {
  return
    ParallelEnumerable.Range(0, list1.Count).Select(i => {
      double n = list1[i] - list2[i];
      return n * n;
    }).Sum();
}

7

solved Which is faster, for loop or LINQ