decimal.TryParse和Convert.ToDecimal+try{} catch{}的性能比较

先说结论:decimal.TryParse性能远远超过try{} catch{},毕竟异常处理非常耗时间,至于decimal.TryParse的内部实现还不清楚,等项目结束再做调查。

源码:

using System;
using System.Diagnostics;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            decimal result;
            string value = "test";
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            for (int i = 0; i < 10000; i++)
            {
                result = decimal.TryParse(value.ToString(), out result) ? result : 0;
            }
            stopwatch.Stop();
            Console.WriteLine(stopwatch.Elapsed.TotalMilliseconds);
            stopwatch.Start();
            for (int i = 0; i < 10000; i++)
            {
                try
                {
                    result = Convert.ToDecimal(value);
                }
                catch
                {
                    result = 0;
                    continue;
                }
            }
            stopwatch.Stop();
            Console.WriteLine(stopwatch.Elapsed.TotalMilliseconds);
            Console.ReadLine();
        }
    }
}

输出:

第一次

2.0262

58126.309

第二次

1.9822

81878.0471

第三次

1.2648

82526.4398

posted @ 2020-12-03 23:01  左崔吉  阅读(223)  评论(0)    收藏  举报