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 i = 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 i = 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 i = 0; (i <= 10000000); i++) {
if (s1.Equals(s2)){
// Do something
}
}
sw.Stop();
Console.WriteLine("s1.Equals(s2) : " + sw.Elapsed.TotalMilliseconds.ToString());

ElionmPosted Feb 7, 2007, 10:46 AM
I have found a much better performance if you use to test string equality this condition if ((s1.Length==s2.Length) && String.Equals(s1,s2)) { // strings are equal ... }
Anh Duc ThaiPosted Jan 30, 2007, 5:40 AM
If i want to compare s1 == "Some string here". What is the good choice?
Mahesh ChandPosted Jan 26, 2007, 9:23 PM
Good reading Kadir. Keep up the good work.