String Concatenation in C#
Tags: programming, coding, csharp, dotnet
Published: 2023-05-05 14:03:00

String concatenation is an operation in which two or more strings are combined into a single string. In C# there are several methods for concatenating strings, each with its advantages and disadvantages.

👉 **Using the `+` operator**

The most straightforward method for concatenating strings is using the `+` operator. This approach is simple and easy to read, making it suitable for small-scale concatenations.

```csharp
var hello = "Hello";
var world = "World";
var result = hello + ", " + world + "!";
```

However, using the `+` operator can have performance implications for large-scale concatenations, as it creates a new string object for each concatenation.

👉 **Using `String.Concat` method**

The `String.Concat` method is another way to concatenate strings. This method accepts multiple string parameters and combines them into a single string.

```csharp
var hello = "Hello";
var world = "World";
var result = string.Concat(hello, ", ", world, "!");
```

This approach is more efficient than using the `+` operator, as it creates fewer intermediate string objects.

👉 **Using `String.Format` method**

The `String.Format` method allows you to concatenate strings while also formatting them, which is particularly useful when you need to insert variable values into a string.

```csharp
var hello = "Hello";
var world = "World";
var result = string.Format("{0}, {1}!", hello, world);
```

This method uses placeholders, such as `{0}` and `{1}`, to indicate where the variable values should be inserted.

👉 **Using `StringBuilder` class**

The `StringBuilder` class is a mutable string representation that can efficiently concatenate strings, especially in scenarios where multiple concatenations are performed within a loop. It is recommended for large-scale concatenations or when performance is a concern.

```csharp
using System.Text;

var hello = "Hello";
var world = "World";

var sb = new StringBuilder();
sb.Append(hello);
sb.Append(", ");
sb.Append(world);
sb.Append("!");

var result = sb.ToString();
```

👉 **Using string interpolation**

Starting from C# 6.0, string interpolation offers a more concise and readable way to concatenate and format strings. It uses the `$` character to indicate an interpolated string, and expressions are enclosed in curly braces.

```csharp
var hello = "Hello";
var world = "World";
var result = $"{hello}, {world}!";
```

## 📏 Benchmark

To evaluate which mode turns out to be the fastest, I ran benchmarks with collections of different sizes (10, 100, 1000) using the [BenchmarkDotNet](https://benchmarkdotnet.org/) library.

Here are the results:

|              Method | NumberOfElements |          Mean |        Error |       StdDev |         Ratio | RatioSD |
|-------------------- |----------------- |--------------:|-------------:|-------------:|--------------:|--------:|
|        PlusOperator |               10 |     188.78 ns |     1.501 ns |     1.404 ns |      baseline |         |
|  StringConcatMethod |               10 |      76.37 ns |     0.373 ns |     0.349 ns |  2.47x faster |   0.02x |
|  StringFormatMethod |               10 |     750.40 ns |     2.852 ns |     2.668 ns |  3.98x slower |   0.03x |
|  StringBuilderClass |               10 |     136.96 ns |     0.357 ns |     0.316 ns |  1.38x faster |   0.01x |
| StringInterpolation |               10 |     181.77 ns |     0.968 ns |     0.906 ns |  1.04x faster |   0.01x |
|        PlusOperator |              100 |   5,783.49 ns |    51.478 ns |    45.634 ns |      baseline |         |
|  StringConcatMethod |              100 |     780.58 ns |     2.756 ns |     2.152 ns |  7.42x faster |   0.06x |
|  StringFormatMethod |              100 |  15,535.48 ns |   112.942 ns |    94.312 ns |  2.68x slower |   0.03x |
|  StringBuilderClass |              100 |     894.24 ns |     1.756 ns |     1.556 ns |  6.47x faster |   0.06x |
| StringInterpolation |              100 |   6,073.78 ns |    47.140 ns |    44.094 ns |  1.05x slower |   0.01x |
|        PlusOperator |             1000 | 434,286.02 ns | 6,218.640 ns | 5,512.662 ns |      baseline |         |
|  StringConcatMethod |             1000 |   7,537.42 ns |    33.887 ns |    31.698 ns | 57.60x faster |   0.65x |
|  StringFormatMethod |             1000 | 631,354.10 ns | 4,463.246 ns | 4,174.923 ns |  1.45x slower |   0.02x |
|  StringBuilderClass |             1000 |   7,266.14 ns |    22.858 ns |    20.263 ns | 59.77x faster |   0.73x |
| StringInterpolation |             1000 | 431,354.97 ns | 2,774.406 ns | 2,595.181 ns |  1.01x faster |   0.01x |

As you can see, the winner in terms of performance is `String.Concat` method. However, it should be noted that as the size of the collection increases, the `StringBuilder` class turns out to be faster.

> ⚠️ **Warning**
> _Keep in mind that you may get different values than those given in the table. This depends on various factors, such as the length and complexity of the input strings, the hardware of the machine on which the code is running, etc._

## 🎯 Conclusion

In this article, we explored various methods of string concatenation in C#, each with its own pros and cons. From the straightforward `+` operator, useful for small-scale concatenations but less efficient for larger volumes, to the `String.Concat` method, which is more efficient in terms of memory management. We also looked at the `String.Format` method for situations requiring formatting and the `StringBuilder` class, ideal for large-scale concatenations or optimizing performance.

My benchmarks show that while the `String.Concat` method is generally faster, the `StringBuilder` class becomes more efficient as the size of the data increases. However, the choice of method depends on various factors such as the size of the text and specific performance needs.

In conclusion, the selection of a concatenation technique in C# should be based on the specific needs of the project, considering both code readability and desired performance.

## 🔗 References

- [How to concatenate multiple strings (C# Guide)](https://learn.microsoft.com/en-us/dotnet/csharp/how-to/concatenate-multiple-strings)