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

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

  • 相关阅读:
    敏捷宣言遵循的原则
    Python学习笔记(11):更多内容
    VBScript之Eval函数与Execute语句(Array.ForEach的实现)
    QTP自动化测试之VBScript对象
    ASP.NET服务器端数据查询控件
    Oracle 日期及GUID
    wp7查询公交路线
    wp7搜索引擎
    在windowsPhone中怎么样存储数据
    客户端PLSQL Developer连接远程数据库Oracle
  • 原文地址:https://www.cnblogs.com/vveiliang/p/6637935.html
Copyright © 2011-2022 走看看