String.Empty,null,Length或String.IsEmptyOrNull?

Pan*_*wal 5 c# string

哪种方式确实是检查空字符串的最快方法,并且有任何特定情况需要任何特定的.

1. String.IsNullOrEmpty()

2. str == null

3. str == null || str == String.Empty

4. str == null || str == ""

5. str == null || str.length == 0
Run Code Online (Sandbox Code Playgroud)

Wil*_*den 19

使用选项1.

如果你特别想检查null或清空字符串,那么就没有理由使用除了之外的任何东西string.IsNullOrEmpty.这是在.NET中这样做的规范方式,并且性能上的任何差异几乎肯定都可以忽略不计.

这是过早优化的教科书范例; 通过各种方式,编写有效的代码,但不要浪费开发时间,因为没有合理的性能提升.请记住,你的时间作为一个开发者通常是远远高于CPU的时间更宝贵.

Quoth Donald Knuth:

我们应该忘记小的效率,大约97%的时间说:过早的优化是所有邪恶的根源.

如果您的应用程序真正需要这种级别的微优化,那么您可能不应该使用.NET.


Zom*_*eep 5

你也关心空白吗?

如果空格有效,则使用String.IsNullOrEmpty,否则使用String.IsNullOrWhiteSpace(在 .Net 4.0 或更高版本中)。后者相当于,但性能更高,String.IsNullOrEmpty(value) || value.Trim().Length == 0;

请参阅http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx