下面我比较两个字符串的代码示例中是否有任何性能优化?
第一的:
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代码只有一个不同:
第一个:
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
第二:
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);
}