Introduction

C## 9 brings an important improvement to anonymous functions by allowing the modifier static on them and we now have static anonymous functions ! Why Microsoft brought this feature ? Because allocation matters ! Microsoft explains here that lambda are not cost less (https://devblogs.microsoft.com/premier-developer/dissecting-the-local-functions-in-c-7/) :

“Anonymous methods are not cheap:”

  • Overhead of a delegate invocation (very very small, but it does exist).
  • 2 heap allocations_ if a lambda captures local variable or argument of enclosing method (one for closure instance and another one for a delegate itself)._
  • 1 heap allocation_ if a lambda captures an enclosing instance state (just a delegate allocation)._
  • 0 heap allocations_ only if a lambda does not capture anything or captures a static state._

#c# #.net 5 #c# 9 #static anonymous function #c++

Introducing C# 9: Static anonymous functions
7.20 GEEK