Junior — Middle
Explain the concept of string interning and why it is used in programming.
sobes.tech AI
Answer from AI
String interning is the process of storing a single copy of each unique string constant in memory, so that all references to the same string point to the same object.
This is used for:
- Saving memory, especially when there are many identical strings.
- Speeding up string comparison operations — instead of comparing character by character, it is enough to compare references.
In C#, string interning is implemented via the String.Intern() method. For example:
string a = "hello";
string b = String.Intern(new string(new char[] { 'h', 'e', 'l', 'l', 'o' }));
bool sameReference = Object.ReferenceEquals(a, b); // true
Here, a and b point to the same string in the intern pool.