In many applications most of the data is of type string, so we need some type of optimization to reduce memory consumption. The common language Runtime implements that optimization, it’s called string interning. CLR keeps an internal hash table called the intern pool where unique references are associated with string literals, with this optimization the CLR avoids creating string object with same literal.
Incase the CLR detects that you are trying to instantiate a string instance with a literal already in the hash table it will use the reference associated with the string literals it won’t allocate new memory.
CLR takes control over decision about which literal to intern and which not to intern, however if we
Let’s look at an example.
The above code Snippets outputs the following:
The reason being that when the first statement is executed an new entry is created in the intern pool hash table with the reference and the literal. When the second statement is created we first check the intern pool and check if the literal exist , if they exist a reference is return else if unique a new entry is created in the intern pool hash table. The second statement will still be created but since their values were found in the intern pool they will NOT be referenced and will get cleaned when the next garbage collection runs.
Manual String Interning
String builder solves the problem of concatenation by making sure that no new string are being created every time a string is concatenated with another. But lets look at this snippet
The string still holds the same value “Hello World” but let’s see the Output.
We get False for the values with the string builder, this is because every time a string builder runs it’s going to allocate a new memory location even if the value are not unique.
To solve this, we can manually intern using the String.Intern() method.
Now all the strings are created from the same memory location as stringone. The memory location created by stringtwo, stringthree and stringfour will be freed for garbage collection process.
IsInterned Method
String.isInterned method returns the interned string or null NOT a Boolean. Here is a code Snippet:
Output
Only the last statement executed and returned the value interned, since in the previous statement the value “Hello World12” is not in the intern pool it returns a null value(empty space)
Conclusion
It’s a great practice to use string interning because it will optimize the application to use less memory since we reference non-unique values only and use garbage collection to clean the object created for unique values.The execution time will also decrease since instead of creating new object we will reference existing.
Top comments (0)