The most efficient way to determine the length of a string! = 0?

I am trying to speed up the following:

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

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

The problem is that .Length actually counts the characters in the string, and that is a lot more than I need. Does anyone have an idea on how to speed this up?

Or is there a way to determine if s [0] exists without checking the rest of the string?

+5
source share
8 answers

EDIT: now that you have provided some more context:

  • , string.Length. - , if, . , , .

  • , string.Split, , .

  • , char . , ?

  • . / , .

:

private static readonly char[] Delimiters = " ".ToCharArray();
private static readonly string[] EmptyArray = new string[0];

public static string[] SplitOnMultiSpaces(string text)
{
    if (string.IsNullOrEmpty(text))
    {
        return EmptyArray;
    }

    return text.Split(Delimiters, StringSplitOptions.RemoveEmptyEntries);
}

string.Length . - , , , , ASCII ( ) . , , O (1), , JIT . ( extern, , , JIT - , .)

, ,

if (s.Length != 0)

- , IMO. :

if (s != "")

, , , . , , , . , , / , , . , , , , . , ?

EDIT: string.IsNullOrEmpty: , , null, . , , .

Length , : , . , , . , null , if. string.IsNullOrEmpty, null , .

+20

String.IsNullOrEmpty .

. Length , .

, , String.IsNullOrEmpty, , , :

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

, , :

if(s != "")
{
    // Do Something
}
+7

Length . .NET .

SSCLI/Rotor , , String.Length (a) (b) :

// Gets the length of this string
//
/// This is a EE implemented function so that the JIT can recognise is specially
/// and eliminate checks on character fetchs in a loop like:
/// for(int I = 0; I < str.Length; i++) str[i]
/// The actually code generated for this will be one instruction and will be inlined.
//
public extern int Length {
    [MethodImplAttribute(MethodImplOptions.InternalCall)]
    get;
}
+5

String.IsNullOrEmpty -

if (!String.IsNullOrEmpty(yourstring))
{
  // your code
}
+3

, , Split:

s.Split(new[]{" "}, StringSplitOptions.RemoveEmptyEntries);
+1

performace: benchmark.

# 3.5 , yourString.Length vs String.IsNullOrEmpty(yourString)

# 4, String.IsNullOrWhiteSpace(yourString)

, , , s[0] , . , , ( s ).

0
        for (int i = 0; i < 100; i++)
        {
            System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
            string s = "dsfasdfsdafasd";

            timer.Start();
            if (s.Length > 0)
            {
            }

            timer.Stop();
            System.Diagnostics.Debug.Write(String.Format("s.Length != 0 {0} ticks       ", timer.ElapsedTicks));

            timer.Reset();
            timer.Start();
            if (s == String.Empty)
            {
            }

            timer.Stop();
            System.Diagnostics.Debug.WriteLine(String.Format("s== String.Empty {0} ticks", timer.ElapsedTicks));
        }

, s.length!= 0 , s == String.Empty

0

String.Split( char [] {''}, StringSplitOptions.RemoveEmptyEntries), .

0

All Articles