问题
Do simple lambda expressions get inlined?
I have a tendency (thanks to F# and other functional forays) to encapsulate repeated code present within a single function into a lambda, and call it instead. I'm curious if I'm incurring a run-time overhead as a result:
var foo = a + b;
var bar = a + b;
vs
Func<T1, T2> op = () => a + b;
var foo = op();
var bar = op();
Which one costs more to run?
回答1:
No. Lambda functions are not inlined but instead are stored as delegates under the hood and incur the same cost of execution as other delegates.
回答2:
To answer the performance question: run it a billion times both ways. Measure the cost of each. Then you'll know. We have no idea what hardware you're using, what "noise" is present in your relevant scenarios, or what you consider to be an important performance metric. You're the only person who knows those things, so you're the only person who can answer the question.
To answer your codegen question: Jared is correct but the answer could be expanded upon.
First off, the C# compiler never does inlining of any code. The jit compiler does do inlining of code, but the fact that the C# compiler generates lambdas as delegate instances means that it is unlikely that the jitter can reasonably inline this code. (It is of course possible for the jitter to do this sophisticated analysis to determine that the same code is always in the delegate, but I do not believe that in practice those algorithms have been implemented.)
If you want the code to be inlined then you should write it in line. If you don't want to write it in line but you still want it inlined then you should write it as a static method and hope the jitter inlines it.
But regardless, this sounds like premature optimization. Write the code the way you want to write the code, and then analyze its performance, and then rewrite the slow stuff.
来源:https://stackoverflow.com/questions/1529390/do-lambdas-get-inlined