Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do closures in c# cause code bloat?

Tags:

c#

clr

Do closures in c# cause code bloat in the generated il? I was told to avoid lambdas with closure variables as they generate hidden classes in the object file that can store the context for the lambda. A class for every lambda with the closed over variables. Is this true? Or does the compiler reuse an existing class, like Tuple or some internal class?

like image 916
Jeremy Bell Avatar asked Nov 29 '22 14:11

Jeremy Bell


1 Answers

Extra classes are only generated when they need to be - when you capture variables other than this. However, this isn't really code bloat in most cases - it's necessary in order to make the delegate work the way you need it to.

In some cases you could write more efficient code yourself, but usually to get a delegate with the same effect, you'd end up writing code which was similar to what the compiler would generate for you... but considerably harder to read.

Most of the time you shouldn't worry about this sort of "bloat" - avoid micro-optimizing for performance to start with - optimize for readability, and measure the performance instead of guessing about it. Then you can attack the bits of code which really matter, and maybe sacrifice a bit of readability for performance there, when you've proved that it's worth it.

(Writing modern C# and deliberately avoiding lambda expressions is like trying to code with one hand tied behind your back. If the person advising you is worried about the "bloat" of closures, you could probably give him a heart attack by showing him the state machine generated for async/await in C# 5...)

like image 126
Jon Skeet Avatar answered Dec 15 '22 05:12

Jon Skeet