一直以来都很好奇TryCatch捕获一个错误会对性能有多大的损耗,有的人说差异是倍数级的,有的人说差异不大,今天忽然心血来潮就自己写了个Demo测试,因为曾经自己写过一篇文章提到不要滥用TryCatch来捕获已知的错误,却没有用事例佐证过,当然结果也是如预期一般。
- static void Main(string[] args)
- {
- int loopCount=100;
- List<string> strList = new List<string>();
- for (int i = 0; i < loopCount; i++) {
- strList.Add("str" + i);
- }
- int intTemp = 0;
- Stopwatch sw2 = new Stopwatch();
- sw2.Start();
- foreach (string str in strList)
- {
- Console.WriteLine("不用TryCatch");
- int.TryParse(str, out intTemp);
- }
- sw2.Stop();
-
- Stopwatch sw = new Stopwatch();
- sw.Start();
- foreach (string str in strList)
- {
- try
- {
- Console.WriteLine("这是TryCatch");
- intTemp = Convert.ToInt32(str);
-
- }
- catch (Exception ex)
- {
-
- }
- }
- sw.Stop();
- Console.WriteLine("循环次数" + loopCount + "不用TryCatch耗时:" + sw2.ElapsedMilliseconds);
- Console.WriteLine("循环次数" + loopCount + "这是TryCatch耗时:" + sw.ElapsedMilliseconds);
- Console.WriteLine("按回车键退出" );
- Console.ReadLine();
- }
|
为了直观地看到每一次转换是否进行了,所以在每一次转换前都输出一次是否用到TryCatch,当loopCount为100时运行结果如下: