C#中內(nèi)聯(lián)函數(shù)的用法介紹
C++ 中有個內(nèi)聯(lián)函數(shù),使用 inline 來修飾函數(shù),編譯器就會對其進行優(yōu)化,將此函數(shù)作為代碼判斷插入到調(diào)用處。
函數(shù)調(diào)用在執(zhí)行時,首先要在棧中為形參和局部變量分配存儲空間,然后還要將實參的值復(fù)制給形參,接下來還要將函數(shù)的返回地址(該地址指明了函數(shù)執(zhí)行結(jié)束后,程序應(yīng)該回到哪里繼續(xù)執(zhí)行)放入棧中,最后才跳轉(zhuǎn)到函數(shù)內(nèi)部執(zhí)行。這個過程是要耗費時間的。
另外,函數(shù)執(zhí)行 return 語句返回時,需要從棧中回收形參和局部變量占用的存儲空間,然后從棧中取出返回地址,再跳轉(zhuǎn)到該地址繼續(xù)執(zhí)行,這個過程也要耗費時間。
而 C# 中可以通過在函數(shù)上使用特性,告訴編譯器要對其進行優(yōu)化,達到相同目的。
[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; } }
測試結(jié)果:
21.92 ns 3.22 ns
到此這篇關(guān)于C#中內(nèi)聯(lián)函數(shù)用法的文章就介紹到這了。希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Unity通過UGUI的Slider調(diào)整物體顏色
這篇文章主要為大家詳細介紹了Unity通過UGUI的Slider調(diào)整物體顏色,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-02-02WPF實現(xiàn)帶模糊搜索的DataGrid的示例代碼
這篇文章主要為大家詳細介紹了WPF如何實現(xiàn)帶模糊搜索的DataGrid,文中的示例代碼講解詳細,具有一定的借鑒價值,需要的可以參考一下2023-02-02c#斐波那契數(shù)列(Fibonacci)(遞歸,非遞歸)實現(xiàn)代碼
c#斐波那契數(shù)列(Fibonacci)(遞歸,非遞歸)實現(xiàn)代碼,需要的朋友可以參考一下2013-05-05