lambda 会内联吗?
简单的 lambda 表达式可以内联吗?
我倾向于(感谢 F# 和其他函数尝试)将单个函数中存在的重复代码封装到 lambda 中,然后调用它。我很好奇是否会因此而产生运行时开销:
var foo = a + b;
var bar = a + b;
vs
Func<T1, T2> op = () => a + b;
var foo = op();
var bar = op();
哪一个运行成本更高?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要回答性能问题:双向运行十亿次。衡量每一项的成本。然后你就会知道了。我们不知道您正在使用什么硬件,您的相关场景中存在哪些“噪音”,或者您认为什么是重要的性能指标。您是唯一知道这些事情的人,因此您是唯一可以回答这个问题的人。
回答您的代码生成问题:贾里德是正确的,但答案可以扩展。
首先,C# 编译器从不内联任何代码。 jit 编译器确实会内联代码,但 C# 编译器生成 lambda 作为委托实例这一事实意味着抖动不太可能合理地内联此代码。 (当然,抖动可能可以进行这种复杂的分析,以确定相同的代码始终在委托中,但我不相信在实践中这些算法已被实现。)
如果您想要内联代码,那么您应该将其编写为行。如果您不想将其编写为行,但仍希望将其内联,那么您应该将其编写为静态方法,并希望抖动将其内联。
但无论如何,这听起来像是过早的优化。想怎么写代码就怎么写,然后分析它的性能,然后重写那些慢的东西。
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.
不会。Lambda 函数不是内联的,而是作为委托存储在底层,并产生与其他委托相同的执行成本。
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.