Speed of Lambda

I have tried many Lambda expression evaluations and enjoyed the reduced coding efforts they provide. But really I would like to evaluate the speed benefits that Lambda provides. In this article I am trying to compare the speed difference of Lambda expressions with traditional programming. The results are mind-blowing.

Simple Scenario : Finding Sum

We have a list of ten thousand numbers and finding the sum n times. The loop will be going for n times each time incrementing the list count.
The sum method with Lambda Expression will be:

private decimal GetSum_Lambda()
      return list1.Sum(); // Using pre-defined method

The core sum method without  Lambda Expression will be:

private decimal GetSum_WithoutLambda()
      decimal sum = 0;
      foreach (decimal d in list2)
      sum += d;

      return sum;

The output is graphically depicted as following.


The red lines in x axis shows the processing time and y axis shows increasing complexity of the test.  Both test complexity are equally distributed.

The above test shows that Lamda expressions for the scenario is almost same. Not too much you might wonder – I agree. But in the following test you will be seeing some surprising outputs.

Complex Scenario : Finding Distinct and then Sum

Shall we move towards a complex scenario?

Here the list has duplicate numbers. We need to remove the duplicate numbers and calculate the sum. This involves the following steps.

1. Remove the duplicates and create the new list
2. Find the sum from new list

The distinct and sum method with lambda expression looks like:

private decimal GetDistinctSum_Lambda()
      return list1.Distinct().Sum();

The distinct and sum method without using lambda expression would be:

private decimal GetDistinctSum_WithoutLambda()
      // Find Distinct
      List<decimal> distinctList = new List<decimal>();
      foreach (decimal number in list2)
            if (!distinctList.Contains(number))

 // Find Sum
decimal sum = 0;
      foreach (decimal d in distinctList)
            sum += d;

return sum;

The output is graphically depicted as following.


Total Time for Lambda: 1 second
Total Time without Lambda: 11 seconds

From the above picture shows that Lambda expression is multiple times faster than the usual approach, as well it is memory efficient too.

Test Application

In the test application, both the simple and complex scenario can be tested using the combo box.

Click the Start button to start the computations. First the left panel computations are executed and then the right. Hope you can execute it.

Please let me know your suggestions or comments on the article.


If we try many examples like this we can identify Lambda is having multiple time performance benefits than traditional programming. So I believe it is worth investing in Functional Programming in C# through Lambda Expressions. Happy Coding.

Up Next
    Ebook Download
    View all
    View all