views:

100

answers:

3

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?

+2  A: 

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
+1  A: 

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

Blindy
+2  A: 

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
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?
wb
@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