"Jon Skeet [C# MVP]" <sk***@pobox.com> a écrit dans le message de
news:11**********************@g49g2000cwa.googlegr oups.com...
s1==s2 has to check for nullity in the operator.
s1.Equals(s2) make a virtual call, which makes the CLR generate code to
do the nullity check anyway. My guess is that that code is faster than
a straight "if (x==null)" kind of check. It's only a guess though.
I decompiled String class.
op_Equality(String, String) wich is what is called with s1==s2, this is the
code that is executed :
public static bool operator ==(string a, string b)
{
return string.Equals(a, b);
}
So let's have a look to String.Equals(string a, string b) :
public static bool Equals(string a, string b)
{
if ((object)a == (object)b) return true;
if ((a != null) && (b != null)) return a.Equals(b);
return false;
}
There is first a test that check if the two strings are the same object in
order not to do a useless comparison
Then, it calls s1.Equals(s2) only if none of s1 and s2 are null.
To conclude, s1==s2 make a call to a function that checks if the objects are
the same, then checks if none are null and then calls s1.Equals(s2);
That's why s1.Equals(s2) is "faster" than s1==s2.
To answer to Jon's guess, I decompiled a code with a 'null' check before
calling s1.Equals(s2);.....it's slower than the code in String.Equals(string
a, string b). Funny isn't it ? Maybe it's because it is not optimised by the
compiler. It doesn't keep in mind the addresses of s1 and s2 so it has to
"load" them twice in the registers.
Hope all of this helps,
Ludovic SOEUR.