The Fastest Way To Compare Two Strings Eqaulity

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());
 
Ebook Download
View all
Learn
View all