调用方法会降低性能吗? [英] Does call method slow down performance?

查看:62
本文介绍了调用方法会降低性能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:
代码1:

For example :
Code 1:

void Main()
{
    Console.WriteLine("Some texts");
}

代码2:

void Main()
{
    Foo();
}

void Foo()
{
    Console.WriteLine("Some texts");
}

代码2的运行速度是否比代码1慢?我虽然在构建发行版时JIT将内联代码2,所以代码2的运行速度将与代码1一样快.但是当我使用

Does code 2 run slower than code 1 ? I though when we build the release the JIT will inline code 2 so then code 2 will run as fast as code 1. But when I test them with LinqPad I got the IL result :

代码1:

IL_0000:  ldstr       "Some texts"
IL_0005:  call        System.Console.WriteLine

代码2:

IL_0000:  ldarg.0     
IL_0001:  call        UserQuery.Foo

Foo:
IL_0000:  ldstr       "Some texts"
IL_0005:  call        System.Console.WriteLine
IL_000A:  ret      

我们可以看到代码2中的IL结果还有一些额外的步骤来调用Foo(),这是否证明代码2的运行速度比代码1慢?

As we can see the IL result in code 2 has some extra steps for calling Foo(), does this prove that code 2 run slower than code 1 ?

推荐答案

首先,您要查看IL,而不是JITted汇编代码.您显示的内容无法证明任何事情.您需要查看JITted输出,以查看JITter是否内联代码.请注意,JITter在不同平台之间(例如,x86与x64)以及Framework的版本与Framework的版本都不同.

First off, you're looking at the IL, not the JITted assembly code. What you have shown doesn't prove anything. You need to look at the JITted output to see if the JITter inlined the code or not. Note that the JITter differes from platform to platform (x86 vs. x64, for example) and version of the Framework to version of the Framework.

第二,当然,因为书面第二版的运行速度比第一版慢.当我说按书面要求"时,我的意思是说这假设JITter尚未内联第二版中的调用.额外的调用增加了一些机器指令,这些指令当然需要花费一些额外的周期来执行(再次,不要忘了我说的是写的!").但是,性能上的差异极其巨大,几乎没有任何意义.您必须在数万亿次迭代和数万亿次迭代的最紧密循环中执行此操作,才能看到有意义的性能差异.

Secondly, of course as written version two will run slower than version one. When I say "as written" I mean that this assumes that the JITter hasn't inlined the call in version two. The extra call adds a few machine instructions which of course take a few extra cycles to execute (again, don't forget I said "as written!"). However the difference in performance is highly extremely magnificently unlikely to be meaningful. You would have to be doing this in the tightest of loops for trillions and trillions of iterations to ever see a meaningful performance difference.

这篇关于调用方法会降低性能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆