string.Empty与"",null的区别,用哪个更好呢?

from:http://www.30wan.com/articleview/2008-5-7/article_view_32502.htm

null是C#要害字,是表示不引用任何对象的空引用的文字值。null是引用类型变量的默认值。那么也只有引用型的变量可以为NULL,假如inti=null,的话,是不可以的,因为Int是值类型的。

string.Empty就相当于"",但他俩和NULL是两码事。

据说是:string.Empty不分配存储空间
""分配一个长度为空的存储空间所以string.Empty比""效率要高点。(效率高是对的,但是到底是否分配存储空间,还不明确,待核实)

一个外国人做了一个测试,测试的对象有5种,分别是:

  • s==“”
  • s==string.Empty
  • s.Equals(”")
  • s.Equals(string.Empty)
  • s.Length==0

    通过下列的测试代码(如要看请点击下面的加号),判定谁的效率更高~

     

    #region测速代码
    intcnTries=10;
    intcnIterations=1000000000;
    =0,fShortQuotes=0,fLongQuotes=0;
    =0,fShortEmpty=0,fLongEmpty=0;
    =0,fShortDotQuotes=0,fLongDotQuotes=0;
    =0,fShortDotEmpty=0,fLongDotEmpty=0;
    =0,fShortDotLength=0,fLongDotLength=0;
    =string.Empty;
    =“Thisisashortstringtotestemptystringcomparison”;
    =“Thisisalongstringtotesttheefficiencyofcomparingwithemptystrings,whichmeansithastobelike,reallylong.AndI’mstartingtorunoutofuselessthingstosay…”;
    =0;j<cnTries; j)
    {

    DateTime.Now;
    =0;i<cnIterations; i)
    {
    ==“”);
    -dtStart;
    =0;i<cnIterations; i)
    {
    ==“”);
    -dtStart;
    =0;i<cnIterations; i)
    {
    ==“”);
    -dtStart;

    DateTime.Now;
    =0;i<cnIterations; i)
    {
    ==string.Empty);
    -dtStart;
    =0;i<cnIterations; i)
    {
    ==string.Empty);
    -dtStart;
    =0;i<cnIterations; i)
    {
    ==string.Empty);
    -dtStart;

    DateTime.Now;
    =0;i<cnIterations; i)
    {
    -dtStart;
    =0;i<cnIterations; i)
    {
    -dtStart;
    =0;i<cnIterations; i)
    {
    -dtStart;

    DateTime.Now;
    =0;i<cnIterations; i)
    {
    string.Empty));
    -dtStart;
    =0;i<cnIterations; i)
    {
    string.Empty));
    -dtStart;
    =0;i<cnIterations; i)
    {
    string.Empty));
    -dtStart;

    DateTime.Now;
    =0;i<cnIterations; i)
    {
    ==0);
    -dtStart;
    =0;i<cnIterations; i)
    {
    ==0);
    -dtStart;
    =0;i<cnIterations; i)
    {
    ==0);
    -dtStart;
    {0}”,fEmptyQuotes/(double)cnTries);
    ...{0}”,fShortQuotes/(double)cnTries);
    ...{0}”,fLongQuotes/(double)cnTries);
    {0}”,fEmptyEmpty/(double)cnTries);
    ...{0}”,fShortEmpty/(double)cnTries);
    ...{0}”,fLongEmpty/(double)cnTries);
    {0}”,fEmptyDotQuotes/(double)cnTries);
    ...{0}”,fShortDotQuotes/(double)cnTries);
    ...{0}”,fLongDotQuotes/(double)cnTries);
    {0}”,fEmptyDotEmpty/(double)cnTries);
    ...{0}”,fShortDotEmpty/(double)cnTries);
    ...{0}”,fLongDotEmpty/(double)cnTries);
    {0}”,fEmptyDotLength/(double)cnTries);
    ...{0}”,fShortDotLength/(double)cnTries);
    ...{0}”,fLongDotLength/(double)cnTries);
    来判定非空字符串是否相等,用s.Length==0来判定是否是空字符串(注重这里不能用这个来判定字符串为NULL的情况,否则会出现“未将对象引用设置到对象的实例”的错误)。

     

    在2.0中判定字符串是否为空(包含NULL的情况)用String.IsNullOrEmpty(str);

  • posted @ 2008-07-24 11:07  农十四  阅读(331)  评论(0编辑  收藏  举报