.NET
StringBuilder
clear contents
C# programming
memory management

best way to clear contents of .NET's StringBuilder

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

The best way to clear a StringBuilder in .NET is usually to keep the instance and remove its current content instead of allocating a new one. In modern .NET, the clearest API is Clear(), and under the hood it is effectively the same idea as setting Length = 0.

Use Clear() when your target framework supports it:

csharp
1using System;
2using System.Text;
3
4class Program
5{
6    static void Main()
7    {
8        var builder = new StringBuilder();
9        builder.Append("Hello");
10        builder.Append(" world");
11
12        builder.Clear();
13
14        builder.Append("Reused");
15        Console.WriteLine(builder.ToString());
16    }
17}

This is readable, direct, and communicates intent clearly.

Equivalent Older Approach

Before Clear() was added, the common technique was:

csharp
builder.Length = 0;

That still works and is effectively the same operation for most practical purposes. It clears the current content without discarding the internal capacity.

csharp
1var builder = new StringBuilder(256);
2builder.Append("temporary text");
3builder.Length = 0;
4builder.Append("next value");

This reuse is exactly why StringBuilder exists in the first place.

Why Reuse Is Often Better Than Reallocation

If you repeatedly create a new StringBuilder inside a hot loop, you generate more allocations and more work for the garbage collector. Reusing an existing builder avoids that churn.

For example:

csharp
1var builder = new StringBuilder();
2
3for (int i = 0; i < 3; i++)
4{
5    builder.Clear();
6    builder.Append("Iteration ");
7    builder.Append(i);
8    Console.WriteLine(builder.ToString());
9}

This pattern is common in logging, CSV generation, protocol formatting, and other repeated string-construction code.

What Clearing Does Not Do

Clearing the builder removes the characters, but it usually does not shrink the underlying buffer. That is often desirable because it makes future appends cheaper. If a builder once grew very large, though, retaining that capacity may waste memory if you no longer need it.

In that case, replacing the instance can make sense:

csharp
builder = new StringBuilder();

Or, if you know the expected future size, recreate it with a more reasonable capacity:

csharp
builder = new StringBuilder(256);

So the real answer is:

  • use Clear() or Length = 0 for normal reuse
  • allocate a new builder only when you intentionally want to drop a large retained buffer

Capacity Matters

You can inspect and adjust capacity if memory usage is important:

csharp
Console.WriteLine(builder.Capacity);
builder.Clear();
builder.Capacity = 256;

Be careful with manual capacity changes. Most code does not need them, and premature tuning can make the code harder to read without any measurable gain.

API Readability Versus Compatibility

If your codebase targets a modern .NET version, Clear() is preferable because it reads like exactly what you mean. If you work in older frameworks or shared code with older APIs, Length = 0 remains perfectly valid.

The performance difference between those two styles is not the real issue. The more important question is whether you should reuse the same builder at all or replace it because of retained capacity.

Common Pitfalls

  • Recreating a new StringBuilder every time when simple reuse would be cheaper.
  • Assuming Clear() also shrinks memory usage back to a minimal size.
  • Manually tuning capacity without evidence that it matters.
  • Keeping a giant builder alive after one unusually large operation.
  • Forgetting that StringBuilder is mutable and should not be shared unsafely across threads.

Summary

  • Use StringBuilder.Clear() as the clearest modern way to empty a builder.
  • 'builder.Length = 0 is the older equivalent and still works.'
  • Clearing removes content but usually keeps the allocated capacity.
  • Reuse the builder for repeated work unless you specifically want to release a large buffer.
  • Choose readability first, then optimize capacity only when measurement justifies it.

Course illustration
Course illustration

All Rights Reserved.