好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C语言中内联函数用法介绍

这篇文章介绍了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 lt; _max; i++) { sum += Method1(); } s1.Stop(); Stopwatch s2 = Stopwatch.StartNew(); for (int i = 0; i lt; _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 ns3.22 ns

关于C#中内联函数使用的文章到此结束。希望对大家的学习有所帮助,也希望大家能支持一下搜源网。

查看更多关于C语言中内联函数用法介绍的详细内容...

  阅读:31次