zoukankan      html  css  js  c++  java
  • String.IsNullOrEmpty和"".length>0 那个更高效

    今天在浏览DevTopics的博客时,发现一篇介绍String的随笔,介绍的是判断一个String变量是否为空时,String的一个方法和一个属性之间的比较,给一个 string变量 's', 下面那个表达式更快?

    1. String.IsNullOrEmpty( s ) 
    2. s == null || s.Length == 0 

    如果你猜第二个,那么你是对的. 它将比String.IsNullOrEmpty方法快15%,但这种也是以百万分之一秒来衡量的!
    这里有一个简单的例子来比较2种方式:

    01using System;
    02   
    03namespace StringNullEmpty
    04{
    05class Program
    06{
    07static void Main( string[] args )
    08{
    09long loop = 100000000;
    10string s = null;
    11long option = 0;
    12long empties1 = 0;
    13long empties2 = 0;
    14   
    15 DateTime time1 = DateTime.Now;
    16   
    17for (long i = 0; i < loop; i++)
    18{
    19 option = i % 4;
    20switch (option)
    21{
    22case 0:
    23 s = null;
    24break;
    25case 1:
    26 s = String.Empty;
    27break;
    28case 2:
    29 s = "H";
    30break;
    31case 3:
    32 s = "HI";
    33break;
    34}
    35if (String.IsNullOrEmpty( s ))
    36 empties1++;
    37}
    38   
    39 DateTime time2 = DateTime.Now;
    40   
    41for (long i = 0; i < loop; i++)
    42{
    43 option = i % 4;
    44switch (option)
    45{
    46case 0:
    47 s = null;
    48break;
    49case 1:
    50 s = String.Empty;
    51break;
    52case 2:
    53 s = "H";
    54break;
    55case 3:
    56 s = "HI";
    57break;
    58}
    59if (s == null || s.Length == 0)
    60 empties2++;
    61}
    62   
    63 DateTime time3 = DateTime.Now;
    64   
    65 TimeSpan span1 = time2.Subtract( time1 );
    66 TimeSpan span2 = time3.Subtract( time2 );
    67 Console.WriteLine( "(String.IsNullOrEmpty( s )): Time={0} Empties={1}",
    68 span1, empties1 );
    69 Console.WriteLine( "(s == null || s.Length == 0): Time={0} Empties={1}",
    70 span2, empties2 );
    71 Console.ReadLine();
    72}
    73}
    74}

     一般我喜欢定义成这样:string a=string.Empty;不用判断是否为null。

  • 相关阅读:
    第四周作业
    第三周作业
    第二周作业
    7-1,求最大值及下标值
    7-1.查找整数
    打印沙漏
    赚了还是亏了
    秋末学期总结
    机器学习小知识
    python 小知识
  • 原文地址:https://www.cnblogs.com/liyonghui/p/2130761.html
Copyright © 2011-2022 走看看