日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C#中內聯函數的用法介紹_C#教程

作者:癡者工良 ? 更新時間: 2022-06-01 編程語言

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

欄目分類
最近更新