这篇文章介绍了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
到此这篇关于C#中内联函数用法的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持得得之家。
沃梦达教程
本文标题为:C#中内联函数的用法介绍


基础教程推荐
猜你喜欢
- C#通过GET/POST方式发送Http请求 2023-04-28
- 京东联盟C#接口测试示例分享 2022-12-02
- C#集合查询Linq在项目中使用详解 2023-06-09
- c#读取XML多级子节点 2022-11-05
- 使用c#从分隔文本文件中插入SQL Server表中的批量数据 2023-11-24
- Unity shader实现多光源漫反射以及阴影 2023-03-04
- C#中类与接口的区别讲解 2023-06-04
- C# – NetUseAdd来自Windows Server 2008和IIS7上的NetApi32.dll 2023-09-20
- c#中利用Tu Share获取股票交易信息 2023-03-03
- C# Winform实现石头剪刀布游戏 2023-01-11