Performance Tip: Checking For Empty String

In all my books and conference sessions I talk about the proper way to test if a string is valid. Microsoft .NET has been around almost two decades and I still see code like this:

if (testValue.Trim() == "")

This code is even wrong since it’s not checking for null. A better way would be like this:

if (testValue == null || testValue.Trim() == "")

While this is valid code, it IS a performance issue. Strings should always be checked using string.IsNullOrEmpty() (the one I use the most) or string.IsNullOrWhiteSpace(). Here is an example:

if (string.IsNullOrEmpty(testValue))

In my testing in .NET Core, using IsNullOrEmpty is 95% faster and in .NET Framework 4.7.1 its 93% faster!