Do lambdas get inlined?

て烟熏妆下的殇ゞ 提交于 2021-01-26 09:04:50

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!