绝大多数的程序员喜欢使用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