In this article we will see some of the interesting facts about data type string.
In this article we will zoom on internals of data type called “string” used in C# language also will see in practical some of the interesting facts. Agenda of this article is to keep it simple in words, short in length and easy to understand by the reader.
Quickly moving with the topic starting it right below. These facts are more pertaining to C# behavior.
Fact 1: Strings are objects and Reference type
Strings in C# are objects and they are not primitive or pre-defined data type. Identifying type of data type is very much simple in C# on Visual Studio. When a data type is defined then hover mouse on declared “string”data type, below image snapshot clearly shows that it belong to class. As object are created out of that class so data type string are termed as reference type. So whenever string data type is declared they are stored on heap within the memory.
Fact 2: Capital “String” VS small “string”
In C#, small “string” is alias ofcapital “String” and are used in two ways. This can be proved when hovered mouse over “string” data type after declaringit you can capital “String” on Visual Studio.
Where to use which one?
For good readability of the code on Visual try declaring any variable then at that time use small “string” data type.
And when string methods are invoke then at that movement use capital “String”.
In order to prove that fresh objects are created for every new value assigned to string variable. We will create following huge loop which will run and while loop program is running will check memory consumption if found it to be increased or expected more than which is currently being consumed or not.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
classProgram
{
staticvoid Main(string[] args)
{
string str = "";
Console.Read();
Console.WriteLine("Started Creating Objects");
for (int j = 0; j < 300000000; j++)
{
str = Guid.NewGuid().ToString();
}
Console.WriteLine("Completed.....");
Console.Read();
}
}
}
Below is the exact comparison of Task Manager shown one before running loop program and other one is while running loop program. If see the value of “ConsoleApplication1.exe *32” under processed of Task Manager while running loop program value are gradually increasing value which is almost double “3168K” if compared with values “1612K” when loop program was not running.
With above demonstration it proves that fresh objects are created whenever string variable “str” are assigned new value in other words string are proved to be immutable.
Fact 4: String supports Intern
As we have learned from Fact 3 that string are immutable and it creates fresh objects whenever variable is assigned to it. There is also a fact that string support intern. For that first let us meaning of “intern” with respect to data type used.
When we have same value of the variable assigned to the string data type then it uses same memory location i.e. it do not create fresh copy of the object and this is termed as Interning.
Now we will see it practically and prove above statement variable whenever assigned to string it do not create fresh copy.
For that go through below mentioned loop source code where we have a constant value given to our variable “str” which is “String with constant value”
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
classProgram
{
staticvoid Main(string[] args)
{
string str = "";
Console.Read();
Console.WriteLine("Started Creating Objects");
for (int j = 0; j < 300000000; j++)
{
str = "String with constant value";
}
Console.WriteLine("Completed.....");
Console.Read();
}
}
}
Above loop source code we will execute which we will run and see memory consumption under the processes of Task Manager. We will check memory consumption before and after running loop program in order to note the changes. If we notice more memory consumption then it means fresh objects are created or less changes/less changes observed then no fresh objects are created.
When loop program runs string data type is “str” declared it first create “str” pointer which assigns value to first variable and as data type is string it will save value on heap memory then again new variable is created and when found same value is assigned to new variable which is already available on heap memory it will not create fresh object. This process will continue again and again till defined loop is finished. Program execution also moves faster which tends to improves overall performance.
Also from the above comparison image it is clear that before running loop program memory consumption is 1512K and while running loop program memory consumption become 1572K which clears that hardly change in memory happen. With this it is clear that fresh object are not created for every new variable when value is constant.
Fact 5: Doing concatenation use StringBuilder
String being immutable in nature when concatenation is done then at that time use “StringBuilder” which would provide execution faster as compared to general way of doing string concatenation. When you have to perform string concatenation where resource utilization is intensive use make use of inbuilt object”StringBuilder”. It will also avoid creation of fresh memory location for every variable to store when value are different.
Let us elaborate above line of text with small practical in our existing loop program. With normal way of doing concatenation for different value fresh new objects will be created and new memory location will be assigned to it.
Run below loop code to demonstrate one by one first with “StringBuilder” and then with normal string and observe it using Task Manager.
Concatenation with StringBuilder object |
Concatenation with Normal String class |
staticvoid Main(string[] args)
{
string str = "";
Console.Read();
StringBuilder strbld = newStringBuilder();
Console.WriteLine("Started Creating Objects");
for (int j = 0; j < 300000000; j++)
{
strbld.Append("String with
constant variable");
}
Console.WriteLine("Completed.....");
Console.Read();
} |
staticvoid Main(string[] args)
{
string str = "";
Console.Read();
// StringBuilder strbld = new StringBuilder();
Console.WriteLine("Started Creating Objects");
for (int j = 0; j < 300000000; j++)
{
str = "String with constant
variable " + str;
}
Console.WriteLine("Completed.....");
Console.Read();
} |
From below code on the left side we have result using StringBuilder and on the right side result using normal working of string.
While working with object of StringBuilder memory consumption increased very rapidly without creating new copy of fresh object. Whereas if we see output for concatenation using normal string class memory consumption will rise slowly in gradual way as every time it creates fresh new objects for every variable and allocates new memory location on heap.
So here the conclusion is that use in-built object called “StringBuilder” for heavy concatenation especially where value are not same.
Fact 6: Strings are thread safe
In order to make “Strings” in C# thread safe whole credit goes to its immutable nature. As “Strings” in C# is made immutable with that assigning same string data type object variable with different value it creates new copy on heap memory.
If you do not know what is thread safe in C#? Go and visit the link to understand it then you will get complete idea of the topic incase if you are new to it.
Basically thread safe are used if your application is going to run on multi-threading environment so that time if string object is manipulated by one thread then other thread when trying to access that string object or assign some value to it may lead undesirable results or even failure of the program.
So by keeping this thing in mind and to avoid such issues in typical scenario for that strings are kept immutable.
Now we are end towards this article of top 6 interesting fact on string data type topic. Hoping that above small knowledge sharing will make large difference in reader’s practical learning.
Recommending to the fresher and midlevel developers to go through once below worth watching fresher project based startup video which is whooping 100 hrs series end to end: -