C#效率优化(2)-- 方法内联

  1、JIT编译器能够经过将方法内联展开(Method Inline Expansion)来提高效率,相似C++中的内联函数(Inline Function),与C++的内联函数不一样的是,C#并不支持内联函数,而是由JIT编译器在运行时自动进行;ide

  1.对于虚方法,若是JIT编译器能够确认调用该方法时变量的运行时类型,支持方法内联;若是不能够确认变量的运行时类型,则不支持方法内联;对于调用空虚方法,与支持方法内联相比,不支持内联用时约长5倍;
※包括虚属性、虚索引器、虚事件都不支持方法内联;
※抽象方法与虚方法在方法内联方面基本一致;函数

  2.对于接口方法,若是使用该类型的变量调用,支持方法内联;若是使用接口类型的变量调用,则不支持方法内联;对于调用空接口方法,与使用类型的变量调用,使用接口的变量调用用时长约8倍:spa

public class MyBaseClass
{
    public virtual void MyFunc() { }
}
public interface IMyInterface
{
    void MyFunc();
}
public class MyClass : MyBaseClass, IMyInterface
{
    public override void MyFunc() { }
}
//使用时:
MyClass myClass = new MyClass();
MyBaseClass myBaseClass = new myBaseClass();
IMyInterface myInterface = myClass;
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
for (int i = 0; i < 1000000000; i++)
{
    myClass.MyFunc();
}
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds); //320
myBaseClass = myClass; //屡次赋值以使JIT编译器没法确认该变量的运行时类型
stopwatch.Restart();
for (int i = 0; i < 1000000000; i++)
{
    myBaseClass.MyFunc();
}
Console.WriteLine(stopwatch.ElapsedMilliseconds); //1600
stopwatch.Restart();
for (int i = 0; i < 1000000000; i++)
{
    myInterface.MyFunc();
}
Console.WriteLine(stopwatch.ElapsedMilliseconds); //2560

  2、其它不会内联的状况:pwa

  1.递归方法;
  2.包含循环语句的方法;
  3.包含异常处理的方法;
  4.方法体的IL代码长度超过32字节的方法;
※能够经过在方法声明中加入命名空间System.Runtime.CompilerServices中的特性MethodImpl来忽略这个条件:code

[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void MyFunc()
{
    //do…
}

 


若是您以为阅读本文对您有帮助,请点一下“推荐”按钮,您的承认是我写做的最大动力!blog

做者:Minotauros
出处:https://www.cnblogs.com/minotauros/递归

本文版权归做者和博客园共有,欢迎转载,但未经做者赞成必须保留此段声明,且在文章页面明显位置给出原文链接,不然保留追究法律责任的权利。索引

相关文章
相关标签/搜索