zoukankan      html  css  js  c++  java
  • Exception引起的性能问题

    先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

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

  • 相关阅读:
    *Integer to English Words
    *Palindrome Linked List
    *Partition List
    Sort Colors
    wireshark tls
    find 路径必须在表达式之前
    http://mozilla.debian.net/
    maven bundle
    xmpp
    xmlns=""
  • 原文地址:https://www.cnblogs.com/vveiliang/p/6637935.html
Copyright © 2011-2022 走看看