Recently I have come across code performing case insensitive comparisons of strings by first performing a conversion to uppercase/lowercase of both strings and comparing the result. Since .NET strings are immutable, the conversion of the string to uppercase or lowercase is not an in place conversion, but results in a new string being created which contains the converted contents. The extra memory allocation increases memory pressure which leads to more frequent garbage collections, which potentially degrades system performance. To demonstrate the point I decided to fire up my performance test harness and throw a few tests at it. Here I will show the results of two of those tests.
For the these tests I used the text from the King James New Testament, I started comparing all the words from one end of the text to the words on the other end. I chose two techniques for comparing the text, the following code demonstrates the two approaches tested.
- if ( _words[i].ToUpper() == _words[j].ToUpper() )
- if ( string.Compare(_words[i], _words[j], true) == 0 )
The following graph shows the results of that test.

The first bar in red is represents the time taken to perform the case insensitive comparison of all the words using the ToUpper technique, the second bar in green represents the time taken to perform the a case insensitive comparison using the string.Compare method.
Other than duration of execution my performance harness also captures a number of other statistics among which is the number of garbage collections initiated during a single run of the test routine. The following table presents these results.
| Test |
Time |
GC |
| Case Insensitive (ToUpper) |
0.41044230481807 |
138 |
| Case Insensitive (Compare) |
0.10624372650714 |
0 |
The table shows that the test using ToUpper invoked the garbage collector 138 times during the duration of the test. while using the Compare method the garbage collector was not required to run at all, in fact there was no evidence of any managed memory allocation taking place at all.
Note: The results of the string.Compare method will vary with different cultures. For the above tests I used the en-US culture. While I do not know the comparison rules used for every culture I am certain that relative to using the ToUpper technique the string.Compare will alway perform much better.