Hacker News new | ask | show | jobs
by MichaelGG 4844 days ago
The C# compiler one-ups F# here, and will cache the delegate for lambdas, so long as they don't capture any locals (that is if it's "lifted") - so lambdas don't necessarily mean an extra object. (Although the LINQ methods need enumerables and enumerators.)
1 comments

When did they introduce caching for lambdas? I've been caching them by hand since I used to see them pop up in CLR Profiler all the time. Is it unable to cache lambdas constructed in member functions because it can't be sure they don't close over 'this'?
It's been years, at least - maybe from the beginning? I just tried a small program with a lambda inside a member function. Works fine, generates IL like:

  IL_0001:  ldarg.0
  IL_0002:  ldsfld     class [mscorlib]System.Func`2<int32,int32> test.Program::'CS$<>9__CachedAnonymousMethodDelegate1'
  IL_0007:  brtrue.s   IL_001c
  // create and store delegate
  IL_001c:  Load delegate from field and call
   
F# will do neat stuff like completely eliminate the lambda, if you're only using it locally. It even does some constant detection across functions, so it can calculate constant functions at compile time. But if not, F# will create a new closure object every time.