Other

The lambda that allocates every time

Daniel Marbach (planetgeek) Daniel Marbach
Other

Closure allocations that kept surfacing in messaging allocation profiles disappear when captured state is passed as an explicit argument. Daniel Marbach walks through an NServiceBus pipeline change that took 20,000 executions from 7.1 ms to 1.6 ms, and when the extra complexity is not worth it.

Key points

  • Capturing `this` or a local forces a delegate or display-class allocation before the callback is even needed, so a cache hit still pays it.
  • In memory profiles, `*__DisplayClass*`, `Func` and `Action` entries point back to the captured state.
  • With the `ConcurrentDictionary.GetOrAdd` overload that takes state as a value tuple, the benchmark drops from 45.8 ns and 64 bytes to 13.4 ns with no allocation.
  • Moving to a local function is not a fix by itself: supplied as a callback, it still produces an instance-bound delegate.
  • Caching the delegate in a constructor field lowers how often it allocates but keeps both the capture and its lifetime.
  • Passing the same values through `object` can trade a closure for a boxing allocation, so a generic state parameter is preferable.

Real-world use

  • An NServiceBus pipeline path that repeats the same closure allocation for every message
  • An Azure Service Bus SDK helper that creates message batches under a per-attempt timeout and retries
  • A `ConcurrentDictionary` factory whose calls mostly hit the cache

This summary was generated by the agent from the original post on Daniel Marbach (planetgeek). The full text and all rights belong to its author and publisher. Go to original

Report this story

Is something wrong with the summary, or do you own this content? Your message comes straight to my inbox.

Type of message

Related stories

Feedback

Found a bug or have an idea? Your message lands straight in my inbox.

Type of message