Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

How can I avoid using closure to wrap an Action with arguments to one that doesn't take parameters, without the overhead of closures.

For example whats a more performant way to achieve this anonymous method, where SomeAction (arg1, arg2) forms a closure.

Action wrappedAction = () => SomeAction(arg1, arg2);
                This is exactly what closures are for! Is this really a performance bottleneck in your program? Why do you think that this code would perform badly?
– Baldrick
                May 23, 2014 at 5:42
                The compiler creates a class, yes. But instantiating the closure object at runtime is extremely fast. And the closure doesn't copy the captured variables. The compiler has already 'hoisted' the relevant variables to the heap (if necessary), so the closure simply grabs references to these hoisted variables. The process at runtime will most likely involve 1 extremely fast managed heap allocation (to create the new closure object), and the copying of 2 references (a few bytes) to use in the underlying method call when the delegate is invoked. That's it.
– Baldrick
                May 24, 2014 at 2:14
                Profile your code - if your application is performing badly, I'm willing to bet this is not the bottleneck!
– Baldrick
                May 24, 2014 at 2:15
                (Note also that managed heap allocation is almost as fast as stack allocation in most cases - and much faster than an equivalent unmanaged allocation) - msdn.microsoft.com/en-us/library/f144e03t(v=vs.110).aspx
– Baldrick
                May 24, 2014 at 2:25
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.