C#中内联函数的用法介绍

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

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

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

1
[MethodImpl(MethodImplOptions.AggressiveInlining)]

示例如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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;
    }
}
 

测试结果:

1
2
21.92 ns
3.22 ns

到此这篇关于C#中内联函数用法的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

posted @ 2023-01-11 11:21  China Soft  阅读(474)  评论(0编辑  收藏  举报