What should I use to checking empty or null string.

TLF
2 min readFeb 11, 2023

--

When we write the code in C#, we have many ways to check the if the string has the value or not (if we don’t want the whitespace).

For example, Following expressions has similar result.

  1. text != null && text.Trim() != string.Empty
  2. text?.Trim() != string.Empty
  3. string.IsNullOrEmpty(text?.Trim())
  4. string.IsNullOrWhiteSpace(text)

At the first glance at these expressions, I think we can say that the 4th expression string.IsNullOrWhiteSpace is the best for readability.

Today we are going to do simple test to check that are there any different on performance wise for these expressions.

I’m going to use https://github.com/dotnet/BenchmarkDotNet for this article.

Source code for bench marking

using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;
using System;

namespace EmptyChecking
{
class Program
{
static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<StringChecker>();
}
}

public class StringChecker
{
private const string MyString = @"Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";

[Benchmark]
public bool ManualCheck() => (MyString != null && MyString.Trim() != string.Empty);

[Benchmark]
public bool ManualCheckWithNullableExpression() => (MyString?.Trim() != string.Empty);

[Benchmark]
public bool IsNullOrEmpty() => (MyString != null && string.IsNullOrEmpty(MyString));

[Benchmark]
public bool IsNullOrWhiteSpace() => string.IsNullOrWhiteSpace(MyString);
}
}

Let’s see the result

We can say that string.IsNullOrEmpty(text?.Trim()) is the best for checking and ten times faster than string.IsNullOrWhiteSpace(text).

if our application is very super sensitive to performance, I think it’s the best to just use IsNullOrEmpty but in the end it’s just a nano seconds so in the most of application I don’t think it’s make that much different.

P.S.

By the way, Is string.IsNullOrEmpty(text?.Trim()) and string.IsNullOrWhiteSpace(text) are identical?

If we take a look at the implementation of Trim() we can see that it also use Char.IsWhiteSpace to check the whitespace which is the same as how IsNullOrWhiteSpace() check the whitespace.

--

--

No responses yet