Most efficient way to determine if a string length

2020-07-05 05:20发布

I'm trying to speed up the following:

string s; //--> s is never null

if (s.Length != 0)
{
   <do something>
}

Problem is, it appears the .Length actually counts the characters in the string, and this is way more work than I need. Anybody have an idea on how to speed this up?

Or, is there a way to determine if s[0] exists, w/out checking the rest of the string?

9条回答
\"骚年 ilove
2楼-- · 2020-07-05 05:50

Just use String.Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries) and it will do it all for you.

查看更多
Rolldiameter
3楼-- · 2020-07-05 05:53

String.IsNullOrEmpty is the preferred method for checking for null or zero length strings.

Internally, it will use Length. The Length property for a string should not be calculated on the fly though.

If you're absolutely certain that the string will never be null and you have some strong objection to String.IsNullOrEmpty, the most efficient code I can think of would be:

if(s.Length > 0)
{
    // Do Something
}

Or, possibly even better:

if(s != "")
{
    // Do Something
}
查看更多
淡お忘
4楼-- · 2020-07-05 05:53

As always with performace: benchmark.
Using C# 3.5 or before, you'll want to test yourString.Length vs String.IsNullOrEmpty(yourString)

using C# 4, do both of the above and add String.IsNullOrWhiteSpace(yourString)

Of course, if you know your string will never be empty, you could just attempt to access s[0] and handle the exception when it's not there. That's not normally good practice, but it may be closer to what you need (if s should always have a non-blank value).

查看更多
登录 后发表回答