Console.WriteLine(string.Format("ReferenceEquals(str1, str2) = {0}", ReferenceEquals(str1, str2)));
Console.WriteLine(string.Format("ReferenceEquals(str1, str3) = {0}", ReferenceEquals(str1, str3)));
Console.WriteLine(string.Format("ReferenceEquals(str1, str4) = {0}", ReferenceEquals(str1, str4))); </pre></div>
Console.WriteLine(string.Format("ReferenceEquals(str1, str2) = {0}", ReferenceEquals(str1, str2)));
Console.WriteLine(string.Format("ReferenceEquals(str1, str3) = {0}", ReferenceEquals(str1, str3))); </pre></div>
str2 = string.Intern(str2);
str3 = string.Intern(str3);
Console.WriteLine(string.Format("ReferenceEquals(str1, str2) = {0}", ReferenceEquals(str1, str2)));
Console.WriteLine(string.Format("ReferenceEquals(str1, str3) = {0}", ReferenceEquals(str1, str3)));</pre></div>
str1 = string.Intern(str1);
Console.WriteLine(string.Format(@"String.IsInterned(str1) = {0}", String.IsInterned(str1) != null));</pre></div>
private static void Test(int testCount, int stringLength)
{
NormalCompare1(string.Empty, string.Empty);
NormalCompare2(string.Empty, string.Empty);
ReferenceCompare(string.Empty, string.Empty);
string str1 = new string('a', stringLength);
string str2 = str1;
Console.WriteLine("testCount = " + testCount.ToString());
Console.WriteLine("stringLength = " + stringLength.ToString());
Console.WriteLine("NormalCompare1...");
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < testCount; i++)
{
NormalCompare1(str1, str2);
}
Console.WriteLine("Elapsed: " + sw.ElapsedMilliseconds.ToString());
Console.WriteLine("NormalCompare2...");
sw.Restart();
for (int i = 0; i < testCount; i++)
{
NormalCompare2(str1, str2);
}
Console.WriteLine("Elapsed: " + sw.ElapsedMilliseconds.ToString());
str1 = string.Intern(str1);
str2 = string.Intern(str2);
Console.WriteLine("ReferenceCompare...");
sw.Restart();
for (int i = 0; i < testCount; i++)
{
ReferenceCompare(str1, str2);
}
Console.WriteLine("Elapsed: " + sw.ElapsedMilliseconds.ToString());
Console.WriteLine(new string('=',50));
}
private static Boolean NormalCompare1(string str1, string str2)
{
return str1 == str2;
}
private static Boolean NormalCompare2(string str1, string str2)
{
return str1.Equals(str2);
}
private static Boolean ReferenceCompare(string str1, string str2)
{
return ReferenceEquals(str1, str2);
}</pre></div>