Working with Strings and StringBuilder in C#

Introduction

In C#, strings are one of the most used data types.
Whenever you work with user input, logs, messages, or database queries, you deal with string manipulation.

However, using the normal string class can become inefficient if you modify text multiple times (for example, concatenating in a loop).
That’s where StringBuilder comes to the rescue — it’s optimized for frequent string changes.

In this article, we’ll explore both String and StringBuilder with real-time ASP.NET WebForms examples, and understand where each should be used.

1. What is a String in C#?

string in C# is an immutable (unchangeable) sequence of characters.

When you modify a string — for example, by concatenating —
C# actually creates a new string object in memory every time.

Example

string name = "Sandhiya";
name += " Priya";  // Creates a new string in memory

C#

This means each modification costs extra memory and CPU time, which becomes inefficient inside loops.

2. What is StringBuilder in C#?

The StringBuilder class (from the System.Text namespace) is a mutable object — meaning it can change the same memory block without creating new string objects each time.

It’s ideal when:

  • You modify strings inside loops

  • You perform many concatenations

  • You generate large text dynamically (like HTML or reports)

3. Namespace Required

using System.Text;

C#

4. Real-Time Example: Compare String vs StringBuilder

Scenario

You are generating 1000 customer names (or messages) dynamically in an ASP.NET WebForm.
Let’s see how performance differs between string and StringBuilder.

ASPX Page (StringVsStringBuilder.aspx)

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

<!DOCTYPE html><html><head>
    <title>Working with Strings and StringBuilder in C#</title></head><body>
    <h2>String vs StringBuilder Example (ASP.NET WebForms)</h2>

    <asp:Button ID="btnCompare" runat="server" Text="Compare Performance" OnClick="btnCompare_Click" />
    <br /><br />
    <asp:Label ID="lblResult" runat="server" ForeColor="Blue"></asp:Label></body></html>

HTML

Code Behind (StringVsStringBuilder.aspx.cs)

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

namespace WebFormsDemo{
    public partial class StringVsStringBuilder : System.Web.UI.Page
    {
        protected void btnCompare_Click(object sender, EventArgs e)
        {
            int count = 10000; // number of concatenations
            Stopwatch sw = new Stopwatch();

            // Using normal string
            sw.Start();
            string str = "";
            for (int i = 0; i < count; i++)
            {
                str += "Customer" + i + " ";
            }
            sw.Stop();
            long stringTime = sw.ElapsedMilliseconds;

            // Using StringBuilder
            sw.Restart();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < count; i++)
            {
                sb.Append("Customer").Append(i).Append(" ");
            }
            sw.Stop();
            long sbTime = sw.ElapsedMilliseconds;

            // Display result
            lblResult.Text = $"<b>String Time:</b> {stringTime} ms<br/>" +
                             $"<b>StringBuilder Time:</b> {sbTime} ms<br/><br/>" +
                             $"StringBuilder is approximately <b>{stringTime / (double)sbTime:0.0}x faster</b>!";
        }
    }}

C#

Output Example

MethodTime Taken (ms)Performance
String480 msSlow (creates new objects repeatedly)
StringBuilder35 msFast (reuses same memory)

Result:
StringBuilder performs much better when performing many concatenations.

5. Real-Time Use Case: Generating Dynamic HTML

Imagine you’re building a Product Report Page in ASP.NET WebForms.
You want to display 50 products in an HTML table dynamically.

If you use string concatenation, it’s slow.
If you use StringBuilder, it’s much faster.

ASPX Page (DynamicHtmlExample.aspx)

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

<!DOCTYPE html><html><head>
    <title>Dynamic HTML Using StringBuilder</title></head><body>
    <h2>Product List Generated Using StringBuilder</h2>

    <asp:Button ID="btnGenerate" runat="server" Text="Generate HTML" OnClick="btnGenerate_Click" />
    <br /><br />
    <asp:Literal ID="litHtml" runat="server"></asp:Literal></body></html>

HTML

Code Behind (DynamicHtmlExample.aspx.cs)

using System;using System.Text;

namespace WebFormsDemo{
    public partial class DynamicHtmlExample : System.Web.UI.Page
    {
        protected void btnGenerate_Click(object sender, EventArgs e)
        {
            // Create a dynamic HTML table using StringBuilder
            StringBuilder html = new StringBuilder();

            html.Append("<table border='1' cellpadding='5' cellspacing='0'>");
            html.Append("<tr><th>Product ID</th><th>Product Name</th><th>Price</th></tr>");

            for (int i = 1; i <= 10; i++)
            {
                html.Append("<tr>");
                html.Append("<td>").Append(i).Append("</td>");
                html.Append("<td>Product ").Append(i).Append("</td>");
                html.Append("<td>₹").Append((i * 150).ToString()).Append("</td>");
                html.Append("</tr>");
            }

            html.Append("</table>");

            // Display in page
            litHtml.Text = html.ToString();
        }
    }}

C#

Output (Displayed on Browser)

Product IDProduct NamePrice
1Product 1₹150
2Product 2₹300
3Product 3₹450
.........

Result:
The table is dynamically generated using StringBuilder, efficiently and cleanly.

6. Key Differences: String vs StringBuilder

FeaturestringStringBuilder
MutabilityImmutableMutable
Memory UsageHigh (creates new object every time)Low (same object reused)
PerformanceSlow for large concatenationsFast and efficient
NamespaceSystemSystem.Text
Use CaseSmall text operationsRepeated string modifications or dynamic content generation

7. When to Use

ScenarioRecommended Type
Small text or few concatenationsstring
Large loops, repeated appendingStringBuilder
Dynamic HTML or SQL Query generationStringBuilder
Fixed text, no modificationstring

8. Conclusion

Both String and StringBuilder are essential in C#,
but understanding when to use each one can greatly improve your web application’s performance and memory efficiency.

Use string for small, simple operations.

Use StringBuilder for loops, dynamic content, or performance-critical code.