String
String is always immutable, the memory will allocate separately whenever we assign new value to that, below is the best example to explain this.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace StringAndStringBuilder
- {
- class Program
- {
- static void Main(string[] args)
- {
- string name = "Ramakrishna";
- name = "Ramakrishna Basagalla";
- }
- }
- }
To explain it better see the below example.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace StringAndStringBuilder
- {
- class Program
- {
- static void Main(string[] args)
- {
- string name = "Ramakrishna";
- for (int i=1;i<=10000;i++) {
- name = "Ramakrishna " + i;
- }
- }
- }
- }
To test this we have a tool called ‘CLR Profiler’, we can download this tool from the Microsoft site, this tool is going to capture how much memory is allocated and it shows options like the memory management graph (How memory is handled by the Garbage Collector).
So let’s run this tool by targeting the application.
I have extracted in my local folder, it will give us two version of the codes (32 and 64 bit codes).

Execute the CLRProfiler and select the Allocation and Calls checkboxes and choose our application exe to run. (Click on Start Application)


Here the application allocated 400,236,631 bytes to store he string names.
As I mentioned string are immutable because to support thread safety, if the string variable is used by different threads we need to create multiple concepts for the string variables.
We can overcome this problem using String Builder.
String Builder
String Builder is mutable, it will update/replace the existing value with new value.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace StringAndStringBuilder
- {
- class Program
- {
- static void Main(string[] args)
- {
- StringBuilder name = new StringBuilder();
- for (int i=1;i<=10000;i++) {
- name.Append("Ramakrishna " + i);
- }
- }
- }
- }
If we run this application using CLRProfiler here are the results.

Here the application allocated bytes is 136,597, it is far better than the string (400,236,631 bytes).
Conclusion
| String | String Builder |
| String are immutable | String Builder is mutable |
| Memory is allocated separately for each assign, it will create separate copy. | It replace the existing one with new one. |
| String are slow compare with String Builder | String Builder is faster than String |
| This will be suggested for less string assign | This will be more useful if you assign values multiple times |

SubashPosted Sep 15, 2016, 6:54 AM
Nice share sir
Shshi Bhooshan SharmaPosted May 1, 2016, 9:34 AM
useful topic