網站首頁 編程語言 正文
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
相關推薦
- 2022-04-11 圖文詳解C#中的協變與逆變_C#教程
- 2022-09-13 Android?Studio實現簡單補間動畫_Android
- 2022-10-20 flutter?material?widget組件之信息展示組件使用詳解_Android
- 2023-01-12 keepalived?+?nginx?實現高可用方案_nginx
- 2022-05-10 ASP.NET?Core使用Log4net實現日志記錄功能_實用技巧
- 2022-08-03 C++實現圖像目標區裁剪ImageCropping_C 語言
- 2022-02-25 C++實現單例模式的方法_C 語言
- 2023-03-20 C#實現拷貝文件到另一個文件夾下_C#教程
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支