2 つの文字列を比較する以下のコード サンプルで、パフォーマンスの最適化はありますか?
初め:
public static bool Compare_01()
{
string str_01 = "a";
string str_02 = "a";
if (str_01 == str_02)
return true;
else
return false;
}
二:
public static bool Compare_02()
{
string str_01 = "a";
string str_02 = "a";
if ((object)str_01 == (object)str_02)
return true;
else
return false;
}
両方とも戻るtrue
。
彼らのilコードには1つだけ違いがあります:
1位:
IL_0001: ldstr "a"
IL_0006: stloc.0 // str_01
IL_0007: ldstr "a"
IL_000C: stloc.1 // str_02
IL_000D: ldloc.0 // str_01
IL_000E: ldloc.1 // str_02
IL_000F: call System.String.op_Equality
2番目:
IL_0001: ldstr "a"
IL_0006: stloc.0 // str_01
IL_0007: ldstr "a"
IL_000C: stloc.1 // str_02
IL_000D: ldloc.0 // str_01
IL_000E: ldloc.1 // str_02
IL_000F: ceq
System.Stringで次のようなものを見つけました:
public static bool Equals(String a, String b) {
// Here
if ((Object)a==(Object)b) {
return true;
}
// ****
if ((Object)a==null || (Object)b==null) {
return false;
}
if (a.Length != b.Length)
return false;
return EqualsHelper(a, b);
}