
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Improving String Comparison Performance
|
71
of the for loop. Characters can be skipped by changing the iterator expression to
increment the
counter variable by more than one. The string can also be iterated in
reverse order by changing the
for loop expressions, as shown:
for (int counter = testStr.Length - 1; counter >= 0; counter--)
{
Console.WriteLine(testStr[counter].ToString( ));
}
The compiler optimizes the use of a foreach loop iterating through a
vector array—one that starts at zero and has only one dimension.
Converting a
foreach loop to another type of loop, such as a for loop,
may not produce any noticeable increases in performance.
It should be noted that each of these methods was compiled using the /optimize
compiler option. However, adding or removing this option has very little impact on
the resulting Microsoft Intermediate Language (IL) code.
2.21 Improving String Comparison Performance
Problem
Your application consists of many strings that are compared frequently. You have
been tasked with improving performance and making more efficient use of resources.
Solution
Use the intern pool to improve resource usage and, in turn, improve performance.
In some cases string interning will not yield the performance improve-
ments that you want. The more string comparisons made in your
application, ...