switch与if效率实例解析·5年以下编程经验必看【C#】
生活随笔
收集整理的這篇文章主要介紹了
switch与if效率实例解析·5年以下编程经验必看【C#】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
絕大多數的程序員喜歡使用if判斷,但是真的效率高嗎?還是其它的,可能只會用if呢!我們今天就具體測一測,用事實說話,測試量100W:
本文采用的是【C#】語言進行測試
switch效率測試代碼:
using System; using System.Diagnostics; namespace Action {class Program{static void Main(string[] args){Random ra = new Random();int count = 1000000;DateTime start = DateTime.Now;for (int i = 0; i < count; i++){switch (ra.Next(10)){case 0:break;case 1:break;case 2:break;case 3:break;case 4:break;case 5:break;case 6:break;case 7:break;case 8:break;case 9:break;default: break;}}DateTime end = DateTime.Now;double usedMemory = Process.GetCurrentProcess().WorkingSet64 / 1024.0 / 1024.0;Console.WriteLine("耗時:"+(end-start).TotalMilliseconds+"毫秒");Console.WriteLine("消耗內存:"+ usedMemory+"M");}} }100W次swtich判斷,消耗時間31.66ms,消耗內存16.31M
if效率測試代碼:
using System; using System.Diagnostics; namespace Action {class Program{static void Main(string[] args){Random ra = new Random();int count = 1000000;DateTime start = DateTime.Now;for (int i = 0; i < count; i++){int v = ra.Next(10);if (v == 0){}else if (v == 1){}else if (v == 2){}else if (v == 3){}else if (v == 4){}else if (v == 5){}else if (v == 6){}else if (v == 7){}else if (v == 8){}else if (v == 9){}}DateTime end = DateTime.Now;double usedMemory = Process.GetCurrentProcess().WorkingSet64 / 1024.0 / 1024.0;Console.WriteLine("耗時:" + (end - start).TotalMilliseconds + "毫秒");Console.WriteLine("消耗內存:" + usedMemory + "M");}} }100W次swtich判斷,消耗時間34.68ms,消耗內存16.30M
結論:
綜上實驗可得:
1、在C#語言中,兩者效率相差不大,幾乎可以忽略不計,在一百萬次判斷中只是相差2~3毫秒,效率還是相當驚人的。
2、很明顯的是【Java】【Python】【C#】三者測試完成后,覺得Java的效率還是最高的。相信,如果換成用Linux服務器效果會更好。
總結
以上是生活随笔為你收集整理的switch与if效率实例解析·5年以下编程经验必看【C#】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: switch与if效率实例解析·5年以下
- 下一篇: 计算某一段程序消耗的内存和时间【C#】