有关C#中使用if else和try catch的问题及效率问题

本来if esle 是流程控制 try catch是异常处理,本身其实是没有可比性的,但是开发过程中有的人很容易混用,而且两者有的时候效果似乎一样,所以我还是用了个简单的测试来简单的比较下。

不多说,直接上代码:页面test.aspx.cs的代码如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using xiejun.Common;

namespace xiejun.test
{
    public partial class test : System.Web.UI.Page
    {
        protected string A = "";//比较try catch 和if else 效率问题
        protected string sTimeStart = "";
        protected string sTimeEnd = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            IfElse();
            TryCatch();
        }

        /// <summary>
        /// if else 方法
        /// </summary>
        private void IfElse() {
            int forCount = 300 * 10000;
            sTimeStart = DateTime.Now.ToString();
            for (int i = 0; i < forCount; i++)
            {
                if (!string.IsNullOrEmpty(Request.QueryString["id"]))
                {
                    A = Request.QueryString["id"].ToString();
                }
                else {
                    A = "不存在参数id";
                }
            }
            sTimeEnd = DateTime.Now.ToString();
            CommonMethods.WriteTxt("开始时间:" + sTimeStart + "结束时间:" + sTimeEnd);
        }
        /// <summary>
        /// try catch方法
        /// </summary>
        private void TryCatch() {
            int forCount = 300 * 10000;
            sTimeStart = DateTime.Now.ToString();
            for (int i = 0; i < forCount; i++)
            {
                try
                {
                    A = Request.QueryString["id"].ToString();
                }
                catch {
                    A = "不错在参数id";
                }
            }
            sTimeEnd = DateTime.Now.ToString();
            CommonMethods.WriteTxt("开始时间:" + sTimeStart + "结束时间:" + sTimeEnd);
        }
    }
}

对比

test.aspx?id=1运行结果

开始时间:2015/4/29 17:15:01结束时间:2015/4/29 17:15:02
开始时间:2015/4/29 17:15:02结束时间:2015/4/29 17:15:02

test.aspx运行结果
开始时间:2015/4/29 17:22:50结束时间:2015/4/29 17:22:51
开始时间:2015/4/29 17:22:51结束时间:2015/4/29 17:23:20

可以看到当运行正常的时候 try catch 和if else 运行300万次效率都在一秒之内,而存在异常的时候try catch所用时间是29秒,if else 只用了1秒钟处理,如果在已知存在的异常下 用try catch 效率足足比if else了将近30倍;

总结:

我们在能够预料到一些基本的异常的时候尽量代码处理 异常 如上 用if else ,只有在存在未知异常的时候 用try catch,在已知存在某些异常的情况下用try catch代替if else做流程控制 是非常不好的习惯,循环次数多的话,差异还是非常明显。

原文地址:https://www.cnblogs.com/net-xiejun/p/4466594.html