Demystifying: What does “Strings are immutable” means?

Introduction

As a programmer sometimes we just accept things and we just do not bother about itJ. One of those sentences which is widely accepted and never questioned is:-

Strings are immutable

You go to any site you will find this sentence without too much in-depth explanation of what exactly it means. Even I am from the same category who was least bothered what this sentence means until.

Until one day I was working on a HTML parser application which had heavy in-memory string concatenation whichwent out of memoryfrequently.

I started hunting around for solution and the solution was nothing other than understanding the above 3 words.  So let's first understand what the above statement actually means.

Let's assume you are looping and concatenating a string variable as shown in thecode given below. Each string concatenation creates fresh copy of variable / memory allocation and the previous copy is sent for garbage collection. In short the below loop allocates different memory blocksfor each concatenation.

In short immutable means cannot be changed.

s1.jpg


Any developer who is smart enough can figure out that this logic is completely absurd. Why Why Why … did Microsoft think this way ?.

Why did Microsoft team think this way?

There's a saying "He who asks a question is a fool for a minute; he who does not remains a fool forever.".  The next question which came to my mind if this is inefficient why did Microsoft thought this way and have they provided alternatives?.

Thanks to stackoverflow the smoke started moving out.

When we use string variables in multithreaded scenarios every thread modification creates new copy of memory which avoidsmulti-threading issues. In other words thread safety gets built-in by itself when fresh copies of data are created.

Multithreading happens one in blue moon

Courtesy :- http://kucinghitamjalanjalan.blogspot.in

s2.jpg

I am least ashamed to say that after 8 years of c# experience, 4years as a trainer (Here's my website for c# training) , I have not worked on a single multi-threaded application.Must be I must have spawned some threads here and there but nothing reallyserious.  Atleast nothing with stringconcatenation.

In simple words if my motive is heavy string concatenation withoptimal usage of memory then "String" is definitely not the option.

Excellent brains that have made c# definitely cannot overlook thisthing and they have not.  Thealternative for such scenario is use "StringBuilder".

"Stringbuilder" are not immutable,putting in other words if you change the data of the variable the same memory location is modified rather than fresh copies of memory getting created. 

Below is a simple image which shows how to use "StringBuilder" and how the memories are allocated internally.


s3.jpg

Trust but verify


Image source from http://darkwing.bombdotcom.net

 s4.jpg

I can see many developer saying till now ,Demo,Demo,Demo ,Demo ….

I understand the same was with me; it was difficult to trust this wholething. Out of curiosity I downloaded CLR profiler and ran test on the belowtwo test code as shown below.

Note:- You can also see thecomplete demo as follows: -

v1.jpg

Below is the sample code for String( test code 1).

 string x = ""; for (inti = 0; i < 10000; i++) // loop this 10000 times
{
    x = "Shiv" + x; 
}


Below is the sample code for StringBuilder( test code 2).

 StringBuilder x = newStringBuilder();
 
for (inti = 0; i < 10000; i++) // Does it create only one copy
{
   x.Append("Shiv"); 
} 


String code ( test code 1) gave me the below sample readings.

s5.jpg

Stringbuilder code( Test code 2) gave the below sample reading.

s6.jpg

Gooosssh, look at the reading 400235631 bytes where allocated for String, while string builder consumed 136597bytes.... Way wayway less.

So next time some says "Strings are immutable" , you know what you are hearing.

Watch the video below for the real demo

If you do not believe what I have written see the actual video demo as follows:-


v1.jpg

The Mumbai c# corner chapter on SSIS / SSAS andThreading chapters

Via this article I would like to make a two big announcement. We have two big events which are happening via Mumbai c# corner group. We have limited seats please register to this event prior to avoid confusion.

First is "ABC of SSIS & SSRS", register to this event now.

Second is "C# threading and synchronization techniques training" , register to this event now.

Be a part of c# corner Mumbai chapter

Are you from Mumbai and want to be part of this user group email us your details @ [email protected]

Finally do not forget to visit my site for c# trainings.


Recommended Free Ebook
Similar Articles