8

I have started to use anonymous delegates a lot in C# and I have begun to wonder how efficient the complier or runtime is in removing them from the code that is actually run and I haven't seen this detailed anywhere?

Is it clever enough at all to inline them and collapse recursive uses that could be statically deduced?

AMissico
  • 21,470
  • 7
  • 78
  • 106
iam
  • 1,623
  • 1
  • 14
  • 28
  • 3
    Can you provide an example of a case that you'd like it to optimize? – SLaks Jun 02 '10 at 14:04
  • 1
    I doubt that the *compiler* does anything to remove them. The JITer however, may perform a variety of optimizations, which may include inlining such functions. – LBushkin Jun 02 '10 at 14:07
  • However, I believe the JITer will not inline delegates. – SLaks Jun 02 '10 at 14:11
  • Well at the most complicated level I was thinking of experimenting with the creation of composite objects through partial functions. That does seem a bit of shame if it can't do that :( – iam Jun 02 '10 at 16:09

3 Answers3

3

No the C# compiler will not optimize a lambda expression into inline code. Anonymous delegates and lambda expressions will always produce a corresponding delegate or an expression tree. This is covered in section 6.5 of the C# language spec

An anonymous-method-expression or lambda-expression is classified as an anonymous function (§7.14). The expression does not have a type but can be implicitly converted to a compatible delegate type or expression tree type

In certain cases the lambda will be cached and not recreated for future use. But it will not be inlined.

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • But does what you quoted actually mean they won't - as it seems to me more conceptionally how they should behave from the users view - not what an optimiser may be able to do behind your back? – iam Jun 02 '10 at 16:12
  • @wb, it does not directly state this but it's a requirement. To be used an anonymous function must be converted to a delegate. Delegate's are first class types in .Net and can be overridenn to do anything on invoke. If the C# compiler inlined a delegate it would potentially bypass a user defined DynamicInvokeImpl which would break behavior hence it cannot inline them. – JaredPar Jun 02 '10 at 16:36
2

In most cases, no, it isn't.

However, unless you're noticing actual performance issues and have tracked them down in a profiler, you shouldn't worry about it.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

The C# compiler will never optimize them. However the .NET JIT compiler might if they're simple enough.

Blindy
  • 65,249
  • 10
  • 91
  • 131