在C#中检查空字符串的最佳方法

问题描述:

检查空字符串的最佳方法是什么(我不是考虑在C#中初始化!),考虑代码性能?(请参见下面的代码)

What is the best way for checking empty strings (I'm not asking about initializing!) in C# when considering code performance?(see code below)

string a;

// some code here.......


if(a == string.Empty)

if(string.IsNullOrEmpty(a))

if(a == "")

任何帮助将不胜感激。 :)

any help would be appreciated. :)

请勿将字符串与 String.Empty 检查空字符串。

Do not compare strings to String.Empty or "" to check for empty strings.

相反,使用 String.Length == 0

Instead, compare by using String.Length == 0

string.Empty 之间的差异很小。 String.Empty 不会创建任何对象,而 会在内存中创建一个用于检查的新对象。因此string.empty在内存管理中更好。
但是与 string.Length == 0 的比较将更快,并且是检查空字符串的更好方法。

The difference between string.Empty and "" is very small. String.Empty will not create any object while "" will create a new object in the memory for the checking. Hence string.empty is better in memory management. But the comparison with string.Length == 0 will be even faster and the better way to check for the empty string.