Difference between String and StringBuilder in C#
String vs StringBuilder

Difference between String and StringBuilder in C#

What does these String and StringBuilder mean in C#?

In C# programming language, both String and StringBuilder are used to handle text, but they work differently:

String (Immutable)

The string is immutable, Immutable means if you create a string object then you cannot modify it and It always creates a new object of string type in memory.

  • String type object is created once, and it cannot be changed (this is what immutable means).
  • Every modification (concatenation, replacement) creates a new string in memory, which can be inefficient or memory costed.

Article content
Picture 1. Example of String

StringBuilder (Mutable)

StringBuilder is mutable, which means if we create a string builder object then you can perform any operation like insert, replace, or concat without creating a new instance every time. it will update the string in one place in memory and doesn't create new space in memory.

  • Efficient for modifications: Can change the text without creating new objects.
  • Recommended for large or frequent text modifications.

Article content
Picture 2. Example of StringBuilder

Benchmarking

Let's do Benchmark test on these two types of String and StringBuilder. Benchmarking measures the performance of your code, application, system, or hardware under specific conditions. The goal is to gather precise data about how the system behaves for metrics like processing speed, memory usage, resource consumption, or throughput and to identify areas where performance can be optimized.

Article content
Picture 3. Example of how to do benchmark test

Run test, and got the result in the screencap below, it's being shown as a table concept:

Article content
Picture 4. Benchmark test result

Summary

To conclude, String is mostly used when changes are rare, and StringBuilder is in case of multiple alterations/modifications.

#Abdulaziz#Orazbaev#abdulaziz-orazbaev

#C#InterviewQuestions&Answers#String#StringBuilder

#Benchmarking#String#StringBuilder

To view or add a comment, sign in

More articles by Abdulaziz Orazbaev

Explore content categories