What's the most efficient way to determine whether an untrimmed string is empty in C#?

前端 未结 8 1588

I have a string that may have whitespace characters around it and I want to check to see whether it is essentially empty.

There are quite a few ways to do this:

8条回答
  •  -上瘾入骨i
    2020-12-16 00:10

    myString.Trim().Length == 0 Took : 421 ms

    myString.Trim() == '' took : 468 ms

    if (myString.Trim().Equals("")) Took : 515 ms

    if (myString.Trim() == String.Empty) Took : 484 ms

    if (myString.Trim().Equals(String.Empty)) Took : 500 ms

    if (string.IsNullOrEmpty(myString.Trim())) Took : 437 ms

    In my tests, it looks like myString.Trim().Length == 0 and surprisingly, string.IsNullOrEmpty(myString.Trim()) were consistently the fastest. The results above are a typical result from doing 10,000,000 comparisons.

提交回复
热议问题