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

通過數據來看,性能差異還是非常非常大的。“不要用異常做邏輯判斷”,寫代碼時要時刻謹記這條原則,否則一不小心就挖坑了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM