C#: Fastest Way to TRIM strings

This will benchmark various techniques to determine in C# .Net: Fastest way to TRIM strings.

Removing all the whitespace at the beginning and/or end of a string. Every programmer at some point needs to do this. The majority, if not all, programmers typically use a built in library or method call. Why not? Simple. Elegant.

But that’s when this Curious Consultant started wondering in C#: what is the fastest way to trim strings?

The Set Up:

I wrote a C# Console application to test multiple techniques.

The code is written in Visual Studio 2013 targeting .Net Framework version 4.5 x64. The source code is available at the end of this blog so you can benchmark it on your own system if you wish.

In a nutshell, the code does the following:

Creates a specified number of strings (1,000, 100,000, 10,000,000, 50,000,000), both 28 & 128 characters long, with a random amount of white space on either end.

Uses one of the techniques below to remove the white space from both the beginning and end of the strings:

T3 won 33% of the time and was in the top two 25% of the time; T0 only won 21% of the time but was in the top two 29% of the time.

When dealing with 50,000,000 strings at least 128 characters, T2 and T6 were consistently among the fastest beating everything else. And by a significant noticeable amount of time. But only for 50,000,000 strings at least 128 characters in length.

For 50,000,000 strings 28 characters in length, T0 and T3 seemed to perform the best consistently.

Final Say:

On my system, unless someone spots a flaw in my test code, the built in C# .Trim() method should be fine for the general populace. It’s not always the fastest or even second fastest, but the average user probably wouldn’t notice.

If you need to micro-optimize where every millisecond counts, there’s no easy answer other than you’ll have to micro-optimize your code and test the various techniques. Or you could hire me to do it for you. 🙂

Lastly, for any application where you’ll need to trim more than 1,000 strings, don’t use Regex as it’s slower by at least a factor of 10.