这需要关闭/删除,因为差异不是他们的 这是我自己的错。但我不想删除自己的问题 因为我可以被封锁所以如果有主持人可以做到这一点 对我来说..
我希望有人能告诉我
之间的性能差异 variable == true
vs true == variable
经过一些测试后,我true == variable
的速度几乎是variable == true
的两倍,也许完全不相关,但我只是想知道。
但经过一些运行后,我看到了以下结果:
'variableTrue == true' vs 'true == variableTrue'
Performance for 'variableTrue == true'
Average: 0.333442949999999 ms
Min: 0.2784 ms
Max: 7.6198 ms
Performance for 'variableTrue == false'
Average: 0.330602419999998 ms
Min: 0.2784 ms
Max: 10.2835 ms
Performance for 'true == variableTrue'
Average: 0.668567990000006 ms
Min: 0.5568 ms
Max: 7.9245 ms
Performance for 'false == variableTrue'
Average: 0.660314390000008 ms
Min: 0.5568 ms
Max: 10.5792 ms
'variableFalse == false' vs 'false == variableFalse'
Performance for 'variableFalse == true'
Average: 0.31614 ms
Min: 0.295 ms
Max: 0.4047 ms
Performance for 'variableFalse == false'
Average: 0.29688 ms
Min: 0.2947 ms
Max: 0.3082 ms
Performance for 'true == variableFalse'
Average: 0.74112 ms
Min: 0.5901 ms
Max: 1.9459 ms
Performance for 'false == variableFalse'
Average: 0.62093 ms
Min: 0.5895 ms
Max: 0.781 ms
Press any key to continue
我在这里测试的代码可以在这里找到 'variable == true' vs 'true == variable'
答案 0 :(得分:4)
没有区别。原因如下:
代码:
public class C {
private bool value = false;
public void M() {
if(value == true)
{
}
if(true == value)
{
}
}
}
生成的内容:
// Fields
.field private bool 'value'
// Methods
.method public hidebysig
instance void M () cil managed
{
// Method begins at RVA 0x2050
// Code size 26 (0x1a)
.maxstack 1
.locals init (
[0] bool, // first bool variable
[1] bool // second bool variable
)
IL_0000: nop
IL_0001: ldarg.0 // load first bool
IL_0002: ldfld bool C::'value' // load value
IL_0007: stloc.0 // store field in first bool
// sequence point: hidden
IL_0008: ldloc.0 // load first bool
IL_0009: brfalse.s IL_000d // branch if false
IL_000b: nop // debug garbage
IL_000c: nop // debug garbage
IL_000d: ldarg.0 // load first bool
IL_000e: ldfld bool C::'value' // load value
IL_0013: stloc.1 // store value in second bool
// sequence point: hidden
IL_0014: ldloc.1 // load second bool
IL_0015: brfalse.s IL_0019 // branch if false
IL_0017: nop
IL_0018: nop
IL_0019: ret
} // end of method C::M
在调试模式下编译,但它并不重要。关键是,两个if
语句完全相同。发行版版本更好":
.field private static bool 'value'
.method private hidebysig static void
Main(
string[] args
) cil managed
{
.entrypoint
.maxstack 8
// [18 13 - 18 31]
IL_0000: ldsfld bool ConsoleA.Program::'value' // Load value
IL_0005: brfalse.s IL_000d // Branch if false
// USED ONLY SO COMPILER WONT COMPLETELY REMOVE IF STATEMENTS
// [20 17 - 20 36]
IL_0007: ldnull
IL_0008: call void [mscorlib]System.GC::KeepAlive(object)
// [23 13 - 23 31]
IL_000d: ldsfld bool ConsoleA.Program::'value' // Load value
IL_0012: brfalse.s IL_001a // Branch if false
// USED ONLY SO COMPILER WONT COMPLETELY REMOVE IF STATEMENTS
// [25 17 - 25 36]
IL_0014: ldnull
IL_0015: call void [mscorlib]System.GC::KeepAlive(object)
// [27 9 - 27 10]
IL_001a: ret
} // end of method Program::Main
答案 1 :(得分:1)