首页 > 技术文章 > Exception引起的性能问题

vveiliang 2017-03-29 08:54 原文

先show一下两段代码,两段代码都能比较好的实现业务逻辑,但是在高并发下,如果传入的参数为空,那么两段代码的性能表现完全不一样。

private static string Get(string filter)
        {
            if (string.IsNullOrEmpty(filter))
                return "Error";
            else
                return "OK";
        }

private static string GetData(string filter)
        {
            if (string.IsNullOrEmpty(filter))
                throw new ArgumentException();
            else
                return "OK";
        }

下面是两个方法各循环1000次代码和结果:

static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 0; i < 1000; i++)
            {
                Get(string.Empty);
            }
            sw.Stop();
            Console.WriteLine("Loop 1000 Get Method :" + sw.ElapsedMilliseconds);

            sw.Start();
            for (int i = 0; i < 1000; i++)
            {
                try
                {
                    GetData(string.Empty);
                }
                catch
                { }
            }
            sw.Stop();
            Console.WriteLine("Loop 1000 GetData Method :" + sw.ElapsedMilliseconds);

            Console.ReadLine();
        }

 

image

通过数据来看,性能差异还是非常非常大的。“不要用异常做逻辑判断”,写代码时要时刻谨记这条原则,否则一不小心就挖坑了。

推荐阅读