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?
Just use
String.Split(new char[]{' '}, StringSplitOptions.RemoveEmptyEntries)
and it will do it all for you.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:
Or, possibly even better:
As always with performace: benchmark.
Using C# 3.5 or before, you'll want to test
yourString.Length
vsString.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).