软件编程
位置:首页>> 软件编程>> C#编程>> C#中内联函数的用法介绍

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

作者:痴者工良  发布时间:2023-04-18 18:29:18 

标签:C#,内联,函数

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

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

另外,函数执行 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

来源:https://www.whuanle.cn/archives/995

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com