MyITBlog.com - IT Professionals Online Journal
 
  Home  |   Site News  |   About Us  |   Privacy  |   FAQ  |   Contact   Add Blog Entry  |  Login  |  Register   
 My Account
Username
Password
Remember me
Lost Password?


 Categories


  HOME  >  ProgrammingPrint


0
Votes
Performance Issue on String Comparison in Programming   
by praveen on 15 Nov 2005, 05:26     Read praveen's Blog
Total Hits: 993    Comments: 0   

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) 
{                                                                                          
    return (stringA.ToUpper() == stringB.ToUpper());    
}                                                                                         

 

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 ToUpper()creates a temporary string, which has to be created and managed by the garbage collector. This takes extra time and use of memory.

 

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)         
{                                                                                                    
    return (string.Compare(stringA, stringB, true,                      
         System.Globalization.CultureInfo.CurrentCulture) == 0);
}                                                                                                    

 

 

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 String.Compare method is over three times as fast as the ToUpper method. If you have code that is performing a lot of string comparisons (especially in a loop) then using String.Compare can make a big difference.

 

 

Happy Programming

        

   Praveen Kumar

         

 

 

 

 

 


 

Post Comment

Copyright © 2008 MyITBlog.com