
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
72
|
Chapter 2: Strings and Characters
string NonInternedStr = new string(characters);
String.Intern(NonInternedStr);
}
public static void CreateInternedStr(StringBuilder strBldr)
{
String.Intern(strBldr.ToString( ));
}
public static void CreateInternedStr(string str)
{
String.Intern(str);
}
public static void CreateInternedStr(string[] strArray)
{
foreach(string s in strArray)
{
String.Intern(s);
}
}
}
Discussion
The CLR automatically stores all string literals declared in an application in an area
of memory called the intern pool. The intern pool contains a unique instance of each
string literal found in your code, which can allow for more efficient use of resources
by not storing multiple copies of strings that contain the same string literal. Another
possible benefit is enhanced speed when making string comparisons. When two
strings are compared using either the
== operator or the Equals instance method of
the
String Class, a test is done to determine whether each string variable reference is
the same. If they are not, then each string’s length is checked. If the lengths of both
strings are equal, each character is compared individually. However, if you can guar-
antee that the references, instead of the string contents, can be compared, much
faster string comparisons can be made. ...