Вопрос

I tried to search for this but couldn't quite find an answer.

I have a method, and inside it there's a code block call very often, so I refactored it into a local Func.

Now because I don't use that code block anywhere else, it makes sense to have this instead of another method.

But is it better, performance-wise, to use another method? Does the Func get allocated or in some other way use extra processing time or memory because it's declared inside the function, or does it get cached or even actually made into a method behind the scenes by the compiler?

I know it sounds like a micro-optimization thing, but in my case, the method gets called very often. So maybe that changes the consideration.

So, basically:

public T CalledVeryOften(...)
{
    Func<...> block = () => ...;

    //code that calls 'block' several times
}

or

public T CalledVeryOften(...)
{        
    //code that calls 'block()' several times
}

private ... block()
{
   ...
}
Это было полезно?

Решение

Nah, there shouldn't be a huge difference in performance. A Func either compiles to a static or instance method depending on whether you use closures.

However, if you can inline the Func code it can increase performance.. maybe. Not sure how to do that though.

By inline, I'm referring to the inline keyword we can have in C++. It tells the compiler to embed the function instructions in that code block. I'm not sure if C# offers that benefit.

Btw, if the private method really belongs to a method block that can be reusable and you are using Func for the sake of performance increase, I'd refactor it back to the way it was.

Другие советы

It is a micro optimisation :) Unless your program is noticeably slowing down to an unacceptable level and profiling determines that the root cause is the fact you're making the function call, then you can consider alternatives.

The overhead really is negligible in the grand scheme of things. I would definitely file this under "Things I need not be concerned about".

Besides, you've probably made your code more readable in the process.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top