|
Performance Issue on String Comparison
As you might be aware that an application performance can be enhanced by efficient coding. I am not sure that how many of us are really aware off, that a good string comparison will really increase the performance. Hence, this article focus on "Performance Issues on String Comparison"
Let us have a look at the sample code snippet which we code daily to do a comparison of two strings
static bool BadCompare(string stringA, string stringB)
In C#, string are basically immutable. Hence stringA.ToUpper() in the previous code snippet will not convert the stringA to uppercase, instead it will create and return a new string entirely, reason being string are immutable in C#. What this means is that each call to
So how do we solve this issue? Let us have a look at the next sample code snippet which will slove this issue and will enhance the performance
static bool GoodCompare(string stringA, string stringB)
This method prevents the creation of unnecessary temporary strings.
The Good Comparison takes 1.69% of the total execution time of the code, while the Bad Comparison takes 5.50% of the total execution time (Tested using nprof).
So the
Happy Programming
Praveen Kumar
| ||||||||||||||||||||||