日期:2014-05-20  浏览次数:20468 次

判断字符串变量str是否为空的一下三种方法哪个性能更优
判断字符串变量str是否为空的一下三种方法哪个性能更优:a、str== " ";b、str==String.Empty;c、str.Length==0;?

据说答案是C,不太明白,请问为什么啊?

谢谢~~

------解决方案--------------------
题目的要求判断str是否为空.
当str对象未分配内存,既str=null时,这个字符串也算为空.

str== " "和str=String.Empty都不能检测str=null的情况
------解决方案--------------------
string.IsNullOrEmpty(str)
最优秀,但不一定是最快!

str.Length==0;
虽然快,但是str为null的时候会抛异常的
------解决方案--------------------
str.Length==0
效率更快
1.使用Length来检查一个字符串是否为空。
计算Length时,只需要检查内部数组的长度,不需要字节比较。而字节比较是比直接计算计算要慢很多的
2.在来看看string的一个构造函数
String (Char[], Int32, Int32)
将 String 类的新实例初始化为由 Unicode 字符数组、该数组内的起始字符位置和一个长度指示的值。
即string对象在本身构造时,就已经有一个参数是长度指示,他对外的表现就是Length
3.我们在来看看String.Empty本质,有一定c++和vb基础的都知道,一个字符串都有一个表示结尾的字节,net环境下也是如此,这个结尾的字节就是String.Empty
4.使用str==String.Empty要比str== " "快速因为String.Empty在内部是个常量

综上:
a、str== " ";
b、str==String.Empty;
c、str.Length==0;
c优于b,b优于a



------解决方案--------------------
using System;
public class strLengthTime
{
public static void Main()
{
string strTest = " ";
string strSub;
for (int i = 0; i < 1000; i++)
{
strSub = i.ToString();
strTest = strTest + strSub;
}
DateTime startTime;
DateTime endTime;
TimeSpan timeCost;
startTime = DateTime.Now;
for (int m = 0; m < 100000000; m++)
{
if (strTest.Length == 0)
{
}
}

endTime = DateTime.Now;
timeCost = endTime - startTime;
System.Console.WriteLine( "strTest.Length Method Costs: " + timeCost.TotalMilliseconds.ToString());
startTime = DateTime.Now;
for (int m = 0; m < 100000000; m++)
{
if (strTest == string.Empty)
{
}
}
endTime = DateTime.Now;
timeCost = endTime - startTime;
System.Console.WriteLine( "String.Empty Method Costs: " + timeCost.TotalMilliseconds.ToString());
startTime = DateTime.Now;
for (int m = 0; m < 100000000; m++)
{
if (strTest == " ")
{
}
}
endTime = DateTime.Now;
timeCost = endTime - startTime;
System.Console.WriteLine( "The Third Method Costs: " + timeCost.TotalMilliseconds.ToString());
Console.ReadLine();
}
}
事实胜于雄辩
------解决方案--------------------
1. C# 和 C++ 不一样:不是采用0结尾的。

2. 由于原因1,调用Length属性(get_Length方法)时,应该不会通过遍历每个字符串直至尾部来取得。而估计是读取String的private字段:m_stringLength。

3. CLR对于字符串常量(注意:常量)采用字符串驻留机制(Microsoft.NET.框架程序设计 12.2.4节):即用一个散列表保存字符串常量。
比如代码:
string s1 = "hello world ";//在散列表中查找“hello world”,结果没找到,就把“hello world”填到了散列表中,并返回引用给s1
string s2 = "hello world ";//找到了“hello world”,返回它的引用给s2
所以,上面的s1和s2指向同一个字符串而非两个

4. 基于原因3, String类在判断两个相等时,先判断两个字符串是否指向同一个,即这是两个引用(Int32 变量)比较,见下面String类的代码:(op_Equality会调用下面的)
public static bool Equals(string a, string b)
{
if (a == b)
{
return true;
}
if ((a != null) && (b != null))