Hacker News new | ask | show | jobs
by kevingadd 4844 days ago
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'?
1 comments

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.