SIGN UP MEMBER LOGIN:    
ARTICLE

Speed of Lambda

Posted by Jean Paul Articles | Coding Best Practices November 01, 2010
In this article I am trying to compare the speed difference of Lambda expressions with traditional programming. The results are mind-blowing.
Reader Level:


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.

lambda1a.png

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))
                  distinctList.Add(number);

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

return sum;
}

The output is graphically depicted as following.

lamba2.gif

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.

Note

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.
 

Login to add your contents and source code to this article
Article Extensions
Contents added by Bobby Lee on Nov 15, 2010
Outstanding work.  Are there any other articles that compare other aspects of using Lamda expressions?
share this article :
post comment
 

Thank You Tim!

Posted by Jean Paul May 11, 2012

Study.Very useful.

Posted by Tim Yang May 11, 2012

Hello Jean, 


I am sorry to say that what you say is plain wrong. It looks like you have not understood the concept of Extension methods. When you call "list.Sum()" in your code, the list is just passed as a parameter to a static function that contains just a plain 'for each' loop summing the elements up. There is no such thing as a LambdaSum (Lamda expressions are not even involved here, the extension methods on IEnumerable are part of LINQ, which in more complex scenatios, allows the use of lambda expressions, which are just inline functions--those are not used for Sum in your example, though). Also, i cannot think of any faster method to sum up arbitrary numbers. You can't get better than the performance of one (in numbers: 1) arithmetic operation per element, can you?

To check my hypothesis I ran your code in a _release_ configuration with >>optimizations enabled<< and what would you expect? As soon as you take the debugger away from the custom implementation it is exactly as fast as the built-in (who would have thought? it's the same code after all!) The difference you saw was because the debugger does not prepare to halt in system library functions--therefore these seemed to operate faster. With optimizations enabled, the custom loop is even a tiny bit faster because you save one method call, but the difference is neglectible.

You really should try this. Go to the project property pages, select the "Build" tab, change the configuration to "Release" and make sure "Optimize code" is enabled. That's what they do for system libraries, too.

Best Regards,
Stefan

Posted by Stefan Noack Nov 08, 2010

Hello Stefan,

I appreciate your attempt to check the code with Reflector.

Although reflector is showing the same kind of code for iterating and finding the sum, the underlying instance of classes in both the cases will be different.  I mean the List and LambdaSum implementation class which is passes as IEnumerable interafce to the Sum extension method in Enumerable.  So the List would be slower comparing with Lambda class, but as they both support IEnumerable - the Sum method would look the same.

Regards,
Jean Paul

Posted by Jean Paul Nov 08, 2010

At least for the first case. Reflector reveals the following implementation of Enumerable.Sum in .NET Framework:

public static decimal Sum(this IEnumerable<decimal> source)
{
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
    decimal num = 0M;
    foreach (decimal num2 in source)
    {
        num += num2;
    }
    return num;
}

I suspect that you ran debug code where nop instructions are inserted between your code lines for the debugger to create breakpoints. I guess there would be no differences if you'd make a realease build with optimizations enabled. The second example is, however, correct. But the used "custom" implementation is of course the least efficient way to solve the problem. Implementing something as fast as the linq expression would take some more code, though. So linq here is really superior. also in the first case i'd prefer linq even if it was slower.

Posted by Stefan Noack Nov 04, 2010
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
    Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
Become a Sponsor