Checking for string contents? string Length Vs Empty String
Which is more efficient for the compiler and the best practice for checking whether a string is blank?
Also, does the answer depend on language?
Yes, it depends on language, since string storage differs between languages.
Length = 0
. [0] == 0
. .IsNullOrEmpty
. Etc.
In languages that use C-style (null-terminated) strings, comparing to ""
will be faster. That's an O(1) operation, while taking the length of a C-style string is O(n).
In languages that store length as part of the string object (C#, Java, ...) checking the length is also O(1). In this case, directly checking the length is faster, because it avoids the overhead of constructing the new empty string.
In .Net:
string.IsNullOrEmpty( nystr );
strings can be null, so .Length sometimes throws a NullReferenceException
链接地址: http://www.djcxy.com/p/4722.html上一篇: 我如何检查字符串是否包含字符和空格,而不仅仅是空白?
下一篇: 检查字符串内容? 字符串长度与空字符串