String vs. StringBuilder: Analyzing Performance with a LeetCode Question in C#

Firat Tonak
3 min readJan 7, 2023

--

In this article, we will discuss String and StringBuilder in C#. A string in C# is immutable, meaning its value cannot be altered once it is created. When a string variable is created, its pointer is stored in stack memory. Should you wish to modify this string variable, the system generates a new string (pointer) and copies the previous string’s data to the new one. This operation incurs a time complexity of O(n²), which can impact performance, especially in scenarios involving frequent string manipulations.

In fact, whenever you modify a string variable in C# — even if the change is as minor as altering a single letter — the system undergoes a process that results in O(n²) time complexity. This is due to the immutable nature of strings in C#, which necessitates the creation of a new string and the copying of existing data for every modification, regardless of its scale.

Indeed, when tackling algorithm problems involving strings, it is advisable to use StringBuilder instead of string in C#.

This is because adding a character to a StringBuilder instance has a time complexity of O(1), making it significantly more efficient for iterative string manipulations.

However, it’s important to note that converting a StringBuilder back to a string results in a time complexity of O(n). This efficiency in handling string operations makes StringBuilder a preferred choice in scenarios where frequent modifications are required.

StringBuilder is indeed a better option in terms of performance, especially when dealing with scenarios that involve frequent modifications to string data. The use of StringBuilder in C# allows for more efficient handling of string operations, as it avoids the costly process of creating new string instances for every modification, which is the case with immutable strings. As a result, StringBuilder significantly reduces the time complexity and improves performance, particularly in algorithmic and computation-heavy applications.

It’s essential to be familiar with basic string operations in C#, as they are often necessary when solving algorithmic problems. Key operations include:

  1. Replace: This method is used to replace a specified character or a substring within a string with another character or substring.
  2. Split: This function divides a string into an array of substrings based on specified delimiters.
  3. Contains: It checks whether a string contains a specific substring or character.
  4. Trim: This method removes all leading and trailing white-space characters from a string.

Understanding and effectively utilizing these operations can greatly enhance your ability to tackle a wide range of algorithm problems that involve string manipulation.

Here is a corrected version: “This problem can be solved more efficiently using the two-pointer technique; however, I will employ a string builder to address the issue.”

If you wish to learn about the Two Pointers Technique, please refer to the article below.

Leetcode: Reverse Words in A String

public class Solution {
public string ReverseWords(string s) {

StringBuilder builder=new StringBuilder();

string[] sArray=s.Split(' ');

if(sArray.Length==0) return s;

for(int i=sArray.Length-1;i>=0;i--)
{
if(sArray[i]!="")
{
if(i!=0)
{
builder.Append(sArray[i]+" ");
}
else
{
builder.Append(sArray[i]);
}
}
}

return builder.ToString().Trim();
}
}

As demonstrated above, we utilized basic string functions and a string builder to solve the problem. This solution has a time complexity of O(n) and a space complexity of O(n). Although the efficiency of the solution is acceptable, it can be further enhanced by applying the two-pointer technique, which you can access here.

In this article, I have endeavored to elucidate the distinctions between String and StringBuilder. It is my hope that this explanation proves to be beneficial.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Firat Tonak
Firat Tonak

Written by Firat Tonak

Seasoned Senior Full-Stack .NET Developer sharing hands-on experience and cutting-edge technologies in comprehensive Full-Stack development. #TechInsights

No responses yet

Write a response