For my Diploma work I need to calculate distance between two vectors.
For example, Euclidean distance is calculated like:

How could it look if I do have two lists with values?

Something like this:

         public double GetDistance(IList<double> firstVector, IList<double> secondVector)
         {
             double sum = 0;
             for (int i = 0; i < firstVector.Count; i++)
             {
                 sum += (firstVector[i] – secondVector[i]) * (firstVector[i] – secondVector[i]);
             }
             return Math.Sqrt(sum);

But, please take a look how sweet this all could be with Lambda Expression:

         public double GetDistance(IList<double> firstVector, IList<double> secondVector)
         {
             double sum = firstVector.Select((x, i) => (x – secondVector[i]) * (x – secondVector[i])).Sum();
             return Math.Sqrt(sum);
         }

Of course main point of this post is not to show all beauty of LE, but either what did happen after I wrote this Lambda expression. Maniacal interest in what is faster to execute and what is the difference in performance of this two methods appeared in my mind, so I prepared few simple tests.

I’ve ran my tests on 1000000 elements and results were such:

  1. Lambda expressions are quite slower than simple loops.
  2. My test showed that primitive loop is faster in about 15-20%.

Also, I played with VS performance analyzer (Analyze -> Launch Performance Wizard…).
It allows me run one version of code (Lambda) and get detailed report, then run another version of code (Loop) and get another report. After that I’m able to compare results seeing performance improvements. So that is good tool.

If you haven't subsribed yet, you can subsribe below: