C
C#11mo ago
DaVinki

❔ Questions regarding delegates and closures

If I had some static objects with a delegate member (Func<byte[], int>) that was assigned an anonymous function on startup, how much slower would calling the delegate be than a regular function after JIT warmup? No closures. This would be a hot path. My second question would be is it possible to capture a variable without going through the whole closure process? The capturing delegate is also a hot path so I want to avoid instantiating any objects for a function call or at least what could effectively be a function call. There's potentially over 150 different ways of doing things and I don't want to create 150+ types to implement or override a function. I believe anonymous functions are the best way to go about it for the programmer's convenience I might be overthinking this or have an inadequate understanding of delegates to know if they're right for the task or right for performance. The data is live and constantly being received which is where the concern for performance comes from
2 Replies
Aaron
Aaron11mo ago
how much slower would calling the delegate be than a regular function after JIT warmup
unless the function would've been inlined otherwise, basically no difference
would be is it possible to capture a variable without going through the whole closure process?
no, closures (in some form) are a requirement to capture variables, unless you can pass them in as parameters (see string.Create)
I believe anonymous functions are the best way to go about it for the programmer's convenience
then use them until proven you need something else
Accord
Accord11mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.