C# String Theory—CSharp String Optimizations
Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio
| CSharp-Online.NET:Articles |
| C# Articles |
| edit |
C# String Optimizations
The C# String class is designed to minimize unnecessary memory allocations. In the process, String operations can provide some unexpected results.
In the first case, two string variables—siteA, siteB—are declared. The first variable is assigned to a string literal ("C# Online.NET"). The second variable is assigned to the first string variable.
String siteA = "C# Online.NET"; String siteB = siteA; Console.WriteLine ("Case 1 ReferenceEquals: " + ReferenceEquals (siteA, siteB)); Console.WriteLine ("Case 1 Equals: " + siteA.Equals (siteB));
| C# String Optimizations (program output) |
| Case 1 ReferenceEquals: True Case 1 Equals: True |
The result is that both string variables point to (reference) the same string—not just the same string value (Equals), but the same actual string (ReferenceEquals or == operator).
In the second case, one of the two string values—siteA—declared in case 1 (above) has its string value changed. One would be forgiven for thinking that both variables would now point to the new string value but to the same string.
siteA = "CSharp-Online.NET"; Console.WriteLine ("Case 2 ReferenceEquals: " + ReferenceEquals (siteA, siteB)); Console.WriteLine ("Case 2 Equals: " + siteA.Equals (siteB));
| C# String Optimizations (program output) |
| Case 2 ReferenceEquals: False Case 2 Equals: False |
However, the result is that the two variables no longer reference the same string (ReferenceEquals or == operator) nor do they have the same string value (Equals).
In the last case, two new string variables are assigned to a new string literal ("en.csharp-online.net"). Here, one might expect that these two variables would reference two different memory locations.
String website1 = "en.csharp-online.net"; String website2 = "en.csharp-online.net"; Console.WriteLine ("Case 3 ReferenceEquals: " + ReferenceEquals (website1, website2)); Console.WriteLine ("Case 3 Equals: " + website1.Equals (website2));
| C# String Optimizations (program output) |
| Case 3 ReferenceEquals: True Case 3 Equals: True |
However, in fact, the string variables reference the same memory location (ReferenceEquals or == operator). This result may seem surprising until you understand the String intern pool.
The intern pool is a list of strings which are currently referenced in your C# application. When a new string is created, then the intern table is checked first to see if that exact string literal already exists in the pool. If it does already exist, then both string variables will reference the same string literal at the same memory location in the intern table. Therefore, only a single copy of a unique string literal is ever created.
See also
|

