What Is Faster In C#: A String Or A StringBuilder?
As a C# developer, your job is to create code that provides the best possible performance for your business or organization. And to do your job well, you’ll need a solid understanding of C# code optimization.
So let’s take a look at concatenating strings.
There are 3 ways you can add strings together in C#. Understanding the differences between these methods will help you pick the correct strategy for every occasion.
Check out the following code, this is an excerpt from a larger performance testing application:
The first method MeasureTestA declares an empty string and then keeps adding characters to the string in a simple loop, using the ‘+’ operator.
The second method MeasureTestB is a bit more refined. It sets up a StringBuilder instance and adds characters with the Append method.
The third method MeasureTestC goes all out. It sets up a character array, and then uses unsafe code to get a pointer to the memory location where the characters are stored. The loop writes new characters directly to memory while incrementing the pointer.
When I run this code, I get the following results: