The Fastest Way To Compare Two Strings Equality

We usually use “==” for string comparing operations. But What if the code will work 10 million times. You must use the best comparing way for minimum time consuming.

We often works with strings when writing codes. Sometimes the case requires to control if two strings are equal or not. And then we usually use the “==” operator to control equality.
If (s1 == s2)
But What if the code will work 10 million times. You must use the best comparing way for minimum time consuming. Run the code below and see which one the best.
The “==” operator is the slowest, and the “s1.Equals(s2)” is the fastest. 
Stopwatch sw = new Stopwatch();
string 
s1 “Some text for testing”;
string 
s2 “Some text for testing.”;
sw.Start();
for 
(int 0(i <10000000)i++) {
    
if (s1 == s2) {
        
//  Do something
    
}
}
sw.Stop()
;
Console.WriteLine(“s1=s2 : ” + sw.Elapsed.TotalMilliseconds.ToString());

sw.Reset();
sw.Start();
for 
(int 0(i <10000000)i++) {
    
if (String.Equals(s1, s2)) {
        
//  Do something
    
}
}
sw.Stop()
;
Console.WriteLine(String.Equals(s1, s2) : ” + sw.Elapsed.TotalMilliseconds.ToString());
sw.Reset();

sw.Start();
for 
(int 0(i <10000000)i++) {
    
if (s1.Equals(s2)){
        
//  Do something
    
}
}
sw.Stop()
;
Console.WriteLine(s1.Equals(s2) : ” + sw.Elapsed.TotalMilliseconds.ToString());

One thought on “The Fastest Way To Compare Two Strings Equality

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s