服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

如何判断字符串是否为空串?


  本文写作缘起于阮的讨论――《fxcop告诉我,检查一个字符串是否为空要用string.length。》。其实用过fxcop的人都知道它会建议你使用string.length属性来判断字符串是否为空串,但你又是否明白其中的缘由呢?今天有点闲,特意写下这篇文章,希望有点帮助。
  
  1. 三种常用的字符串判空串方法:
  length法:bool isempty = (str.length == 0);
  empty法:bool isempty = (str == string.empty);
  general法:bool isempty = (str == "");
  
  2. 深入内部机制:
  要探讨这三种方法的内部机制,我们得首先看看.net是怎样实现的,也就是要看看.net的源代码!然而,我们哪里找这些源代码呢?我们同样有三种方法:
  rotor法:一个不错的选择就是微软的rotor,这是微软的一个源代码共享项目。
  mono法:另一个不错的选择当然就是真正的开源项目mono啦!
  reflector法:最后一个选择就是使用反编译器,不过这种重组的代码不一定就是原貌,只不过是一种“近似值”,你可以考虑使用reflector这个反编译器[1]。
  这里我采用reflector法,我们先来看看一下源代码[2](片段):
  
  public sealed class string : icomparable, icloneable, iconvertible, ienumerable, icomparable
  {
  static string()
  {
  string.empty = "";
  
  // code here
  }
  
  // code here
  
  public static readonly string empty;
  
  public static bool operator ==(string a, string b)
  {
  return string.equals(a, b);
  }
  
  public static bool equals(string a, string b)
  {
  if (a == b)
  {
  return true;
  }
  if ((a != null) && (b != null))
  {
  return string.equalshelper(a, b);
  }
  return false;
  }
  
  private static unsafe bool equalshelper(string ao, string bo)
  {
  // code here
  
  int num1 = ao.length;
  if (num1 != bo.length)
  {
  return false;
  }
  
  // code here
  }
  
  private extern int internallength();
  
  public int length
  {
  get
  {
  return this.internallength();
  }
  }
  
  // code here
  }
  
  rotor里面string类的代码与此没什么不同,只是没有equalshelper方法,代之以如下的声明:
  
  public extern bool equals(string value);
  
  进一步分析:
  首先是empty法,由于string.empty是一个静态只读域,只会被创建一次(在静态构造函数中)。但当我们使用empty法进行判空时,.net还会依次展开调用以下的方法,而后两个方法内部还会进行对象引用判等!
  
  public static bool operator ==(string a, string b);
  
  public static bool equals(string a, string b);
  
  private static unsafe bool equalshelper(string ao, string bo);
  
  若使用general法判等的话,情况就“更胜一筹”了!因为.net除了要依次展开调用上面三个方法之外,还得首先创建一个临时的空字符串实例,如果你要进行大量的比较,这恐怕是想一想就很吓人了!
  而对于length法,我们就可以绕过上面这些繁琐的步骤,直接进行整数(字符串长度)判等,我们知道,大多数情况下,整数判等都要来得快(我实在想不出比它更快的了,在32位系统上,system.int32运算最快了)!
  另外,我们还可以看到,在equalshelper方法里面.net会先使用length法来进行判等!可惜的是我无法获得internallength方法的代码。但我在mono的源代码里面看到更简明的实现:
  
  class string
  {
  private int length;
  
  public int length
  {
  
  get
  {
  return length;
  
  }
  }
  
  // .
  }
  
  然而使用length法进行字符串判空串时,有一点要注意的,就是你必须先判断该字符串实例是否为空引用,否则将会抛出nullreferenceexception异常!于是,我们有了一个经过改进的length法:
  
  void foo(string bar)
  {
  if ((bar != null) && (bar.length == 0))
  //
  }
  
  3. 最后总结:
  从上面的分析我们可以看到,使用length法来进行字符串判空串是有着很大的性能优势的,尤其在进行大量字符串判空时!当然首先得判断字符串实例是否为空引用!
  
  有关reflector的介绍可以参见《reflector: get the secret inside .net assemblies.》一文。
  本代码反编译自版本号为2.0.3600.0的.net framework。

扫描关注微信公众号