string.IsNullOrEmpty (string) vs. string.IsNullOrWhiteSpace (string) 확인할 때

.NET 4.0 이상에서 string.IsNullOrEmpty(string)문자열을 확인할 때 사용 하는 것이 나쁜 습관으로 간주 string.IsNullOrWhiteSpace(string)됩니까?



답변

가장 좋은 방법은 가장 적합한 방법을 선택하는 것입니다.

.Net Framework 4.0 Beta 2에는 문자열에 대한 새로운 IsNullOrWhiteSpace () 메서드가있어 IsNullOrEmpty () 메서드를 일반화하여 빈 문자열 외에 다른 공백도 포함합니다.

“공백”이라는 용어에는 화면에 표시되지 않는 모든 문자가 포함됩니다. 예를 들어 공백, 줄 바꿈, 탭 및 빈 문자열은 공백 문자 * 입니다.

참조 : 여기

성능면에서 IsNullOrWhiteSpace는 이상적이지 않지만 좋습니다. 메소드 호출은 약간의 성능 저하를 초래합니다. 또한 IsWhiteSpace 메서드 자체에는 유니 코드 데이터를 사용하지 않는 경우 제거 할 수있는 몇 가지 간접 지침이 있습니다. 항상 그렇듯이 조기 최적화는 악의적 일 수 있지만 재미 있습니다.

참조 : 여기

소스 코드 확인 (참조 소스 .NET Framework 4.6.2)

IsNullorEmpty

[Pure]
public static bool IsNullOrEmpty(String value) {
    return (value == null || value.Length == 0);
}

IsNullOrWhiteSpace

[Pure]
public static bool IsNullOrWhiteSpace(String value) {
    if (value == null) return true;

    for(int i = 0; i < value.Length; i++) {
        if(!Char.IsWhiteSpace(value[i])) return false;
    }

    return true;
}

string nullString = null;
string emptyString = "";
string whitespaceString = "    ";
string nonEmptyString = "abc123";

bool result;

result = String.IsNullOrEmpty(nullString);            // true
result = String.IsNullOrEmpty(emptyString);           // true
result = String.IsNullOrEmpty(whitespaceString);      // false
result = String.IsNullOrEmpty(nonEmptyString);        // false

result = String.IsNullOrWhiteSpace(nullString);       // true
result = String.IsNullOrWhiteSpace(emptyString);      // true
result = String.IsNullOrWhiteSpace(whitespaceString); // true
result = String.IsNullOrWhiteSpace(nonEmptyString);   // false

답변

실제 차이점 :

string testString = "";
Console.WriteLine(string.Format("IsNullOrEmpty : {0}", string.IsNullOrEmpty(testString)));
Console.WriteLine(string.Format("IsNullOrWhiteSpace : {0}", string.IsNullOrWhiteSpace(testString)));
Console.ReadKey();

Result :
IsNullOrEmpty : True
IsNullOrWhiteSpace : True

**************************************************************
string testString = " MDS   ";

IsNullOrEmpty : False
IsNullOrWhiteSpace : False

**************************************************************
string testString = "   ";

IsNullOrEmpty : False
IsNullOrWhiteSpace : True

**************************************************************
string testString = string.Empty;

IsNullOrEmpty : True
IsNullOrWhiteSpace : True

**************************************************************
string testString = null;

IsNullOrEmpty : True
IsNullOrWhiteSpace : True

답변

그것들은 다른 기능입니다. 상황에 따라 필요한 것이 무엇인지 결정해야합니다.

나는 그것들 중 하나를 나쁜 습관으로 사용하는 것을 고려하지 않습니다. 대부분의 시간 IsNullOrEmpty()이면 충분합니다. 그러나 당신은 선택이 있습니다 🙂


답변

다음은 두 메소드의 실제 구현입니다 (dotPeek를 사용하여 디 컴파일)

[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
    public static bool IsNullOrEmpty(string value)
    {
      if (value != null)
        return value.Length == 0;
      else
        return true;
    }

    /// <summary>
    /// Indicates whether a specified string is null, empty, or consists only of white-space characters.
    /// </summary>
    /// 
    /// <returns>
    /// true if the <paramref name="value"/> parameter is null or <see cref="F:System.String.Empty"/>, or if <paramref name="value"/> consists exclusively of white-space characters.
    /// </returns>
    /// <param name="value">The string to test.</param>
    public static bool IsNullOrWhiteSpace(string value)
    {
      if (value == null)
        return true;
      for (int index = 0; index < value.Length; ++index)
      {
        if (!char.IsWhiteSpace(value[index]))
          return false;
      }
      return true;
    }

답변

그것은 모두 IsNullOrEmpty()흰색 간격을 포함하지 않는다고 말합니다 IsNullOrWhiteSpace()!

IsNullOrEmpty()문자열이 다음과
같은 경우 : -Null
-Empty

IsNullOrWhiteSpace()문자열이 다음과
같은 경우 : -Null
-Empty-
공백 만 포함


답변

IsNullOrEmpty 및 IsNullOrwhiteSpace로이를 확인하십시오.

string sTestes = "I like sweat peaches";
    Stopwatch stopWatch = new Stopwatch();
    stopWatch.Start();
    for (int i = 0; i < 5000000; i++)
    {
        for (int z = 0; z < 500; z++)
        {
            var x = string.IsNullOrEmpty(sTestes);// OR string.IsNullOrWhiteSpace
        }
    }

    stopWatch.Stop();
    // Get the elapsed time as a TimeSpan value.
    TimeSpan ts = stopWatch.Elapsed;
    // Format and display the TimeSpan value. 
    string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
        ts.Hours, ts.Minutes, ts.Seconds,
        ts.Milliseconds / 10);
    Console.WriteLine("RunTime " + elapsedTime);
    Console.ReadLine();

IsNullOrWhiteSpace가 훨씬 느리다는 것을 알 수 있습니다.


답변

string.IsNullOrEmpty (str)-문자열 값이 제공되었는지 확인하려는 경우

string.IsNullOrWhiteSpace (str)-기본적으로 이것은 이미 일종의 비즈니스 로직 구현입니다 (예 : “”는 좋지 않지만 “~~”와 같은 것이 좋은 이유).

나의 충고 – 비즈니스 로직과 기술적 점검을 혼용하지 마십시오. 예를 들어, string.IsNullOrEmpty는 메소드 시작시 입력 매개 변수를 확인하는 데 가장 좋습니다.