c# 判断空字符串的效率问题

1、判断空字符串大概有如下方法

1、 stirng.IsNullOrEmpty()
2、 和 String.IsEmpty 比较
3、 和 "" 比较
4、 用String.Equal("")比较,字符串变量不能为null,否则报异常,效率次至
5、 用String.Length == 0 判断,字符串变量不能为null,否则报异常, 效率最高

 

   static void Main(string[] args)
        {

            Stopwatch timeWatch = new Stopwatch();
            string strTest = string.Empty;

            ///方法一  string.length 判断,字符串不能为null
            timeWatch.Start();
            for (int index = 0; index < 10000000; index++)
            {
                if (strTest.Length == 0)
                {


                }
            }
            timeWatch.Stop();
            Console.WriteLine(timeWatch.Elapsed + ":string.length耗时");

            ///方法二 string.Equals("") 判断 ,字符串不能为null
            timeWatch.Start();
            for (int index = 0; index < 10000000; index++)
            {
                if (strTest.Equals(""))
                {


                }
            }
            timeWatch.Stop();
            Console.WriteLine(timeWatch.Elapsed + ":string.Equals()耗时");


            ///方法三 string.Empty 判断,  字符串可以为null
            timeWatch.Start();
            for (int index = 0; index < 10000000; index++)
            {
                if (strTest==  string.Empty)
                {

                }
            }
            timeWatch.Stop();
            Console.WriteLine(timeWatch.Elapsed + ":string.Empty耗时");

            ///方法四 "" 判断
            timeWatch.Start();
            for (int index = 0; index < 10000000; index++)
            {
                if (strTest == "")
                {


                }
            }
            timeWatch.Stop();
            Console.WriteLine(timeWatch.Elapsed + ":\"\"比较耗时");

            ///方法五 string.IsNullOrEmpty 判断
            
            timeWatch.Start();
            for (int index = 0; index < 10000000; index++)
            {
                if (string.IsNullOrEmpty(strTest))
                {


                }
            }
            timeWatch.Stop();
            Console.WriteLine(timeWatch.Elapsed + ":string.IsNullOrEmpty耗时");


            /*说明:== 运算符和Equal() 函数功能是一样的,二者都是对值进行了比较 .net类库string类的源码如下
             public static bool operator == (String a, String b) {
             return String.Equals(a, b);
             }*/
            Console.ReadKey();
        }

2、 执行结果如下图

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值