C#  

Working with String, StringBuilder, and StringBuffer in C#

Introduction

In day-to-day ASP.NET C# web applications, we handle lots of text manipulation — like generating reports, building dynamic HTML, or processing user data.

C# provides several ways to handle text:

  • string – basic immutable text type.

  • StringBuilder – mutable and high-performance text manipulator.

  • StringBuffer – not built-in in C#, but conceptually similar to Java’s version — can be simulated using StringBuilder in a thread-safe way.

In this article, we’ll:

  1. Understand how string, StringBuilder, and StringBuffer (conceptually) work.

  2. Compare them using real-time ASP.NET WebForms examples.

  3. Measure performance and thread-safety differences.

1. Understanding the Difference

FeaturestringStringBuilderStringBuffer (conceptual)
MutabilityImmutableMutableMutable
Thread-SafeYes (because immutable)No (not thread-safe)Yes
PerformanceSlow for repeated modificationsFastModerate (slower due to locking)
NamespaceSystemSystem.Text(Simulated using lock + StringBuilder)

2. What Is “StringBuffer” in C#?

Unlike Java, C# does not have a built-in StringBuffer.
However, we can simulate it by making StringBuilder thread-safe using locking (to prevent multiple threads from modifying text at the same time).

Example

private static readonly object lockObj = new object();
private static StringBuilder buffer = new StringBuilder();

public static void SafeAppend(string text)
{
    lock (lockObj)
    {
        buffer.Append(text);
    }
}

This behaves like a StringBuffer — thread-safe version of StringBuilder.

3. Real-Time Example: Generating Dynamic Report in ASP.NET WebForms

Let’s create an ASP.NET WebForm to compare all three types by generating a dynamic Employee Salary Report.

ASPX Page (StringOperationsExample.aspx)

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="StringOperationsExample.aspx.cs" Inherits="WebFormsDemo.StringOperationsExample" %>

<!DOCTYPE html>
<html>
<head>
    <title>String vs StringBuilder vs StringBuffer</title>
</head>
<body>
    <h2>Working with String, StringBuilder and StringBuffer in ASP.NET</h2>

    <asp:Button ID="btnGenerate" runat="server" Text="Generate Report" OnClick="btnGenerate_Click" />
    <br /><br />
    <asp:Label ID="lblResult" runat="server" ForeColor="Blue"></asp:Label>
</body>
</html>

Code Behind (StringOperationsExample.aspx.cs)

using System;
using System.Diagnostics;
using System.Text;
using System.Threading;

namespace WebFormsDemo
{
    public partial class StringOperationsExample : System.Web.UI.Page
    {
        protected void btnGenerate_Click(object sender, EventArgs e)
        {
            int records = 5000;
            Stopwatch sw = new Stopwatch();

            // ================================
            // 1. Using String
            // ================================
            sw.Start();
            string report1 = "";
            for (int i = 1; i <= records; i++)
            {
                report1 += $"Employee {i}, Salary: ₹{i * 1000}\n";
            }
            sw.Stop();
            long stringTime = sw.ElapsedMilliseconds;

            // ================================
            // 2. Using StringBuilder
            // ================================
            sw.Restart();
            StringBuilder sb = new StringBuilder();
            for (int i = 1; i <= records; i++)
            {
                sb.Append("Employee ").Append(i).Append(", Salary: ₹").Append(i * 1000).Append("\n");
            }
            sw.Stop();
            long sbTime = sw.ElapsedMilliseconds;

            // ================================
            // 3. Simulated StringBuffer (Thread-Safe StringBuilder)
            // ================================
            sw.Restart();
            SafeStringBuffer buffer = new SafeStringBuffer();
            for (int i = 1; i <= records; i++)
            {
                buffer.AppendSafe($"Employee {i}, Salary: ₹{i * 1000}\n");
            }
            sw.Stop();
            long bufferTime = sw.ElapsedMilliseconds;

            // ================================
            // Display Results
            // ================================
            lblResult.Text = $"<b>Number of Records:</b> {records}<br/><br/>" +
                             $"<b>String:</b> {stringTime} ms (Slow, Immutable)<br/>" +
                             $"<b>StringBuilder:</b> {sbTime} ms (Fast, Mutable)<br/>" +
                             $"<b>StringBuffer:</b> {bufferTime} ms (Thread-Safe)<br/><br/>" +
                             $"StringBuilder is approximately <b>{stringTime / (double)sbTime:0.0}x faster</b> than String.";
        }
    }

    // ================================
    // Custom StringBuffer Simulation
    // ================================
    public class SafeStringBuffer
    {
        private StringBuilder _builder = new StringBuilder();
        private readonly object _lock = new object();

        public void AppendSafe(string text)
        {
            lock (_lock)
            {
                _builder.Append(text);
            }
        }

        public override string ToString()
        {
            return _builder.ToString();
        }
    }
}

Output Example

TypeTime (ms)Description
String420 msCreates a new object on every change (slow)
StringBuilder30 msUses same object (very fast)
StringBuffer (simulated)40 msThread-safe but slightly slower due to locking

Result

  • StringBuilder is best for performance.

  • StringBuffer (safe builder) is useful for multi-threaded operations like background logging or report generation in web apps.

4. Real-Time Use Cases

Real-Time ScenarioRecommended TypeReason
Combining user input stringsstringSimple, small usage
Generating HTML reports, logs, JSON dataStringBuilderFast and efficient
Logging data from multiple threads (e.g., async tasks)StringBuffer (custom thread-safe builder)Prevents race conditions
Building large SQL queries dynamicallyStringBuilderHigh performance
Displaying repeated labels or valuesStringBuilderMemory efficient

5. Visual Flow of Execution

User clicks “Generate Report”
        ↓
Server executes C# logic
        ↓
String → creates many objects (slow)
StringBuilder → uses same memory (fast)
StringBuffer → uses lock (safe for threads)
        ↓
Result displayed instantly on the page

6. Conclusion

  • string → best for small text, simple concatenations.

  • StringBuilder → best for large text or loops (HTML, reports, logs).

  • StringBufferthread-safe version of StringBuilder, useful for multi-threaded operations.

Understanding these three helps you build faster, cleaner, and scalable ASP.NET WebForms applications. 🚀