Skip to content
  • English Deutsch

benjamin-abt.com

Performance is a feature | Cloud - AI - Azure - .NET - Sustainability

  • Home
  • Blog
  • Portfolio
    • Overview
    • Workshops & Training
    • Publications
  • Contact
  • Home
  • Blog

Efficiently clean a string with .NET

Efficiently clean a string with .NET
May 28, 2024 6 min read BEN ABT
Csharp .NET

Strings are one of the most commonly used types in .NET applications - and very often the source of inefficient code. For example, cleaning up a string - such as removing invalid or non-visible characters - is one of the most common use cases for user input. Unfortunately, the most convenient, but not the most efficient, implementation imaginable is used in this case: Linq.

See full sample here: Sustainable Code by BEN ABT on GitHub

String Manipulation

The most inefficient option, as already mentioned, is direct string manipulation with Linq. Unfortunately, I see this variant by far the most.

C#
string.Concat(source.Where(c => char.IsControl(c) is false))
Shell
1| Method                 | Runtime  | Mean       | Ratio | RatioSD | Gen0   | Gen1   | Allocated | Alloc Ratio |
2|----------------------- |--------- |-----------:|------:|--------:|-------:|-------:|----------:|------------:|
3| Linq                   | .NET 8.0 | 1,646.5 ns |  3.47 |    0.03 | 0.0782 |      - |    1.3 KB |        1.07 |

String Builder

The StringBuilder is significantly faster, as it works directly on the memory area of the string and is therefore very efficient.

C#
 1StringBuilder sb = new();
 2
 3foreach (char c in source)
 4{
 5    if (char.IsControl(c) is false)
 6    {
 7        sb.Append(c);
 8    }
 9}
10
11return sb.ToString();
Shell
1| Method                 | Runtime  | Mean       | Ratio | RatioSD | Gen0   | Gen1   | Allocated | Alloc Ratio |
2|----------------------- |--------- |-----------:|------:|--------:|-------:|-------:|----------:|------------:|
3| StringBuilder_Instance | .NET 8.0 |   860.0 ns |  1.81 |    0.02 | 0.2270 | 0.0019 |   3.71 KB |        3.04 |

The disadvantage at this point is that the StringBuilder must be initialized in addition to the actual operation, which is why we also have an additional Gen1 allocation. However, this disadvantage can be optimized by pooling, so that this takes about 15% less time than the instance variant and about 50% less than the Linq variant.

C#
1| Method                 | Runtime  | Mean       | Ratio | RatioSD | Gen0   | Gen1   | Allocated | Alloc Ratio |
2|----------------------- |--------- |-----------:|------:|--------:|-------:|-------:|----------:|------------:|
3| StringBuilder_Pool     | .NET 8.0 |   706.2 ns |  1.49 |    0.02 | 0.0744 |      - |   1.22 KB |        1.00 |

Span

The span implementation has been available in .NET for almost seven years, but it is still often not used. Admittedly, the barrier to entry of understanding Span and the somewhat “low level” approach doesn’t make it easy, but the results speak for themselves.

The four different span implementations are all faster and more efficient by a large margin; led by an unsafe implementation, which however cannot be used in all scenarios; for example when unsafe code blocks are not possible or allowed.

Shell
1| Method                 | Runtime  | Mean       | Ratio | RatioSD | Gen0   | Gen1   | Allocated | Alloc Ratio |
2|----------------------- |--------- |-----------:|------:|--------:|-------:|-------:|----------:|------------:|
3| Span                   | .NET 8.0 |   394.4 ns |  0.83 |    0.01 | 0.0744 |      - |   1.22 KB |        1.00 |
4| Span1                  | .NET 8.0 |   474.7 ns |  1.00 |    0.00 | 0.0744 |      - |   1.22 KB |        1.00 |
5| Span2                  | .NET 8.0 |   411.8 ns |  0.87 |    0.01 | 0.0744 |      - |   1.22 KB |        1.00 |
6| Span2Unsafe            | .NET 8.0 |   375.1 ns |  0.79 |    0.01 | 0.0744 |      - |   1.22 KB |        1.00 |
C#
 1public static string UsingSpan(string source)
 2{
 3    int length = source.Length;
 4    char[]? rentedFromPool = null;
 5
 6    // allocate
 7    Span<char> buffer = length > 512 ?
 8        (rentedFromPool = ArrayPool<char>.Shared.Rent(length)) : (stackalloc char[512]);
 9
10    // filter
11    int index = 0;
12    foreach (char c in source)
13    {
14        if (char.IsControl(c) is false)
15        {
16            buffer[index] = c;
17            index++;
18        }
19    }
20
21    // only return the data that was written
22    string data = buffer.Slice(0, index).ToString();
23
24    // cleanup
25    if (rentedFromPool is not null)
26    {
27        ArrayPool<char>.Shared.Return(rentedFromPool, clearArray: true);
28    }
29
30    return data;
31}

Sustainable Code

Sustainable code is becoming increasingly important - this should not be neglected, especially in migration projects. This is the best opportunity to implement sustainable code from the ground up.

You can find the complete example of how to clean up strings efficiently here and more examples of sustainable implementation of everyday code with C# and .NET under https://github.com/BenjaminAbt/SustainableCode .

Shell
 1BenchmarkDotNet v0.13.12, Windows 10 (10.0.19045.4412/22H2/2022Update)
 2AMD Ryzen 9 5950X, 1 CPU, 32 logical and 16 physical cores
 3.NET SDK 9.0.100-preview.3.24204.13
 4  [Host]   : .NET 8.0.5 (8.0.524.21615), X64 RyuJIT AVX2
 5  .NET 8.0 : .NET 8.0.5 (8.0.524.21615), X64 RyuJIT AVX2
 6  .NET 9.0 : .NET 9.0.0 (9.0.24.17209), X64 RyuJIT AVX2
 7
 8
 9| Method                 | Runtime  | Mean       | Ratio | RatioSD | Gen0   | Gen1   | Allocated | Alloc Ratio |
10|----------------------- |--------- |-----------:|------:|--------:|-------:|-------:|----------:|------------:|
11| StringBuilder_Pool     | .NET 8.0 |   706.2 ns |  1.49 |    0.02 | 0.0744 |      - |   1.22 KB |        1.00 |
12| StringBuilder_Instance | .NET 8.0 |   860.0 ns |  1.81 |    0.02 | 0.2270 | 0.0019 |   3.71 KB |        3.04 |
13| Linq                   | .NET 8.0 | 1,646.5 ns |  3.47 |    0.03 | 0.0782 |      - |    1.3 KB |        1.07 |
14| Span                   | .NET 8.0 |   394.4 ns |  0.83 |    0.01 | 0.0744 |      - |   1.22 KB |        1.00 |
15| Span1                  | .NET 8.0 |   474.7 ns |  1.00 |    0.00 | 0.0744 |      - |   1.22 KB |        1.00 |
16| Span2                  | .NET 8.0 |   411.8 ns |  0.87 |    0.01 | 0.0744 |      - |   1.22 KB |        1.00 |
17| Span2Unsafe            | .NET 8.0 |   375.1 ns |  0.79 |    0.01 | 0.0744 |      - |   1.22 KB |        1.00 |
18|                        |          |            |       |         |        |        |           |             |
19| StringBuilder_Pool     | .NET 9.0 |   616.3 ns |  1.19 |    0.01 | 0.0744 |      - |   1.22 KB |        1.00 |
20| StringBuilder_Instance | .NET 9.0 |   715.9 ns |  1.39 |    0.01 | 0.2270 | 0.0019 |   3.71 KB |        3.04 |
21| Linq                   | .NET 9.0 | 1,663.5 ns |  3.22 |    0.02 | 0.0782 |      - |    1.3 KB |        1.07 |
22| Span                   | .NET 9.0 |   404.9 ns |  0.78 |    0.01 | 0.0744 |      - |   1.22 KB |        1.00 |
23| Span1                  | .NET 9.0 |   516.1 ns |  1.00 |    0.00 | 0.0744 |      - |   1.22 KB |        1.00 |
24| Span2                  | .NET 9.0 |   398.9 ns |  0.77 |    0.01 | 0.0744 |      - |   1.22 KB |        1.00 |
25| Span2Unsafe            | .NET 9.0 |   389.4 ns |  0.75 |    0.01 | 0.0744 |      - |   1.22 KB |        1.00 |

Related articles

Containerizing .NET in 2026 Without a Dockerfile

Oct 20, 2026 - 11 min read

Containerizing .NET in 2026 Without a Dockerfile

Most .NET Dockerfiles repeat the same five steps: restore, publish, select the matching Microsoft runtime image, copy the output and start …

Problem Details in ASP.NET Core and .NET 11

Oct 5, 2026 - 12 min read

Problem Details in ASP.NET Core and .NET 11

builder.Services.AddProblemDetails() registers infrastructure. It does not create an error contract. An ASP.NET Core request can fail during …

Resilience in .NET with Microsoft.Extensions.Resilience

Sep 21, 2026 - 11 min read

Resilience in .NET with Microsoft.Extensions.Resilience

Retries are the most visible resilience strategy and the easiest one to misuse. Repeating a failing call can recover from a short network …


BEN ABT

BEN ABT

Ben is Chief Engineering Officer and Principal Software Engineer at Medialesson.de, with a strong focus on .NET and Microsoft Azure. In his professional role, he designs and builds highly scalable platforms for hybrid and cloud-based scenarios. He also advises companies and C-levels on migrating to the sovereign cloud.

He runs myCSharp.de, the largest and most active German-speaking C# community forum, actively contributes to both his own and external open-source projects and regularly shares his knowledge through his blog, at community events, conferences and as a writer for technical magazines.

Let's Work Together

Looking for an experienced Platform Architect or Engineer for your next project? Whether it's cloud migration, platform modernization or building new solutions from scratch - I'm here to help you succeed.

New Platforms

Modernization

Training & Consulting

Contact Me
X Facebook LinkedIn WhatsApp
Back Next Blog Post

Open for work!

Contact Me
BEN ABT BEN ABT Software Engineer · Microsoft MVP Passionate about .NET, Azure, performance optimization and sustainable software engineering.

Medialesson GmbH Logo

Microsoft MVP Logo

Recent posts

View all
Stop Using nginx as Your Default Static File Server in Docker

Stop Using nginx as Your Default Static File Server in …

Oct 24, 2026
Containerizing .NET in 2026 Without a Dockerfile

Containerizing .NET in 2026 Without a Dockerfile

Oct 20, 2026
Problem Details in ASP.NET Core and .NET 11

Problem Details in ASP.NET Core and .NET 11

Oct 5, 2026
Resilience in .NET with Microsoft.Extensions.Resilience

Resilience in .NET with Microsoft.Extensions.Resilience

Sep 21, 2026
What Matters in ASP.NET Core 11

What Matters in ASP.NET Core 11

Sep 14, 2026

Tags

.NET (192) Csharp (96) ASP.NET Core (48) Azure (41) DevOps (17) Docker (14) Microsoft (14) EF Core (11) Microsoft MVP (11) AI (10) GitHub (10) GitHub Copilot (10) ASP.NET (9) Security (9) Synology (9) Architecture (8) Raspberry (8) Azure Functions (7) Cloudflare (7) Bicep (6)
benjamin-abt.com

About BEN

Benjamin Abt is a Software Engineer, Platform Architect and Microsoft MVP specializing in .NET, Azure, cloud architecture, performance optimization and sustainable software development.

Connect

  • Follow me on GitHub
  • Follow me on LinkedIn
  • Follow me on Mastodon
  • Microsoft MVP profile
  • Follow SchwabenCode on GitHub
  • Follow me on X

Quick Links

  • Portfolio
  • Blog
  • Workshops & Training
  • Publications
  • Get in Touch
  • Sitemap
Open for Work

© Copyright Benjamin Abt & SchwabenCode | 2011 - 2026

Content licensed under CC BY 4.0 unless otherwise noted.

  • Impressum
  • Privacy
  • Contact