Author: Amol Shrestha
String is immutable. We cannot change the content of a string. For example,
var str = “This is a test”.
Here, str points to a location where the content of the string is located.
If we append something to the string like:
str += “and it does not matter much”.
Now, the str does not point to the same memory address. Rather str points to a new address and the content is “This is a test and it does not matter much”.
Referring to StringBuilder, if we append something to it, it does not amend the address and is cost-effective in terms of resource allocation.
So, when to use the string?
If we visit the basics, string is an array of character.
For example;
string temp = “Aylesbury”
for(int i = 0; i < 9; i++)
{
Console.WriteLine(temp[i] + “\n”);
}
The above will print all the characters in a new line.
How to optimize resource usage with string?
For that we need to refer to string interning.
For example,
var tmp = string.Intern(“Hello World”);
Here, any reference to “Hello World” will result in the address of tmp. The hash of the string content is the key and address is the value of the hashtable.
If we want to find if a string has been interned, we can use
var interned = string.IsInterned(tmp);
If the string is added to the intern pool, content of the string is returned and if not null is returned.
The string literals are interned by default.
For example
string tmp = “OK”;
is interned by default.
But
var tmp = 123;
var temp = 123.ToString();
Here temp is not interned.
At Dogma Group, we help you harness the power of CRM, ERP & related technology for success.
If you have any questions or queries, just call our friendly team on 01296 328689 or drop us an email at info@dogmagroup.co.uk. Our team will be more than pleased to discuss these with you.