C# Method Call Depth Performance
C# Method Call Depth Performance
Compare the performance of method call depths. Reducing call depth can improve speed.
Method calls can be nested. This impacts performance. The more nesting, the more depth to the stack. A method call will require stack space unless it is inlined. By flattening the call stack, we reduce stack usage and improve performance.
And: When a method terminates, its memory is forgotten from the stack and the pointer is readjusted.
Next: This program contains eight important methods: A1 through D1, and A2 through D2.
Info: When A1 is called, it calls B1 and then B1 calls C1. On the other hand, when A2 is called, it simply calls B2, C2, and D2.
Important: The A2 method should consume less stack space. It has a shorter stack.
using System; using System.Diagnostics; class Program { const int _max = 100000000; static void Main() { A1(); A2(); var s1 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { A1(); } s1.Stop(); var s2 = Stopwatch.StartNew(); for (int i = 0; i < _max; i++) { A2(); } s2.Stop(); Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000 * 1000) / _max).ToString("0.00 ns")); Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000 * 1000) / _max).ToString("0.00 ns")); Console.Read(); } static int _i = 1; static void A1() { B1(); } static void B1() { if (_i == 0) throw new Exception(); C1(); } static void C1() { if (_i == 0) throw new Exception(); D1(); } static void D1() { if (_i == 0) throw new Exception(); } static void A2() { B2(); C2(); D2(); } static void B2() { if (_i == 0) throw new Exception(); } static void C2() { if (_i == 0) throw new Exception(); } static void D2() { if (_i == 0) throw new Exception(); } }
Output
3.54 ns Nested calls
0.96 ns Sequential calls
Also: The Exception throws in the program are to confuse the inliner in the JIT.
However: This is likely not useful except on performance-critical parts of important programs.
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2019-04-10 111. Minimum Depth of Binary Tree
2019-04-10 asp.net tag
2019-04-10 CssClass="Hidden"和Visible="False"
2019-04-10 What is the difference between visibility:hidden and display:none?
2019-04-10 ID vs UniqueID vs ClientID in webform
2019-04-10 GitLab community edition
2018-04-10 设置断点后,查看堆栈信息,判断错误调用的来源是哪里