C# 中的内联函数

2020年7月7日 9396点热度 4人点赞 3条评论
内容纲要

C++ 中有个内联函数,使用 inline 来修饰函数,编译器就会对其进行优化,将此函数作为代码判断插入到调用处。

摘自 C语言中文网
函数调用在执行时,首先要在栈中为形参和局部变量分配存储空间,然后还要将实参的值复制给形参,接下来还要将函数的返回地址(该地址指明了函数执行结束后,程序应该回到哪里继续执行)放入栈中,最后才跳转到函数内部执行。这个过程是要耗费时间的。

另外,函数执行 return 语句返回时,需要从栈中回收形参和局部变量占用的存储空间,然后从栈中取出返回地址,再跳转到该地址继续执行,这个过程也要耗费时间。

而 C# 中可以通过在函数上使用特性,告诉编译器要对其进行优化,达到相同目的。

    [MethodImpl(MethodImplOptions.AggressiveInlining)]

示例如下:

using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;

class Program
{
    const int _max = 10000000;
    static void Main()
    {
        int sum = 0;
        Stopwatch s1 = Stopwatch.StartNew();
        for (int i = 0; i < _max; i++)
        {
            sum += Method1();
        }
        s1.Stop();

        Stopwatch s2 = Stopwatch.StartNew();
        for (int i = 0; i < _max; i++)
        {
            sum += Method2();
        }

        s2.Stop();
        Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000000) /
            _max).ToString("0.00 ns"));
        Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000000) /
            _max).ToString("0.00 ns"));
        Console.Read();
    }

    static int Method1()
    {
        return "one".Length + "two".Length + "three".Length +
            "four".Length + "five".Length + "six".Length +
            "seven".Length + "eight".Length + "nine".Length +
            "ten".Length;
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    static int Method2()
    {
        return "one".Length + "two".Length + "three".Length +
            "four".Length + "five".Length + "six".Length +
            "seven".Length + "eight".Length + "nine".Length +
            "ten".Length;
    }
}

测试结果:

21.92 ns
3.22 ns

痴者工良

高级程序员劝退师

文章评论