首页 > 解决方案 > 在 VB .net 中,“如果 x = false”或“如果不是 x”更快

问题描述

全部,

在 VB .net 中,我通常测试 True 或 False 场景,如下所示:

' dict is a dictionary
If dict.ContainsKey(anID) = False Then
   ' Do something
End If

我知道这个测试也可以这样写:

' dict is a dictionary
If not dict.ContainsKey(anID) Then
   ' Do something
End If

我经常想知道一种方法是否比另一种更快?我在互联网上搜索过,但没有找到这两种方法的任何比较。我倾向于使用第一个示例,因为我认为它更易于阅读,但如果有人有证据表明第二种方法更快,我会很感兴趣。通常,这些嵌入在可能迭代数千次的循环中,所以我认为在这种情况下我会将性能置于易读性之上。

标签: vb.netperformance

解决方案


这些通过 ildasm 生成了相同的中间代码。

这是我尝试过的代码:

Sub Main()
    Dim x As Boolean
    If x = False Then
        Console.WriteLine("hello world")
    End If
End Sub

而这第二个代码

Sub Main()
    Dim x As Boolean
    If Not x Then
        Console.WriteLine("hello world")
    End If
End Sub

两者都产生这个

.method public static void  Main() cil managed
{
  .entrypoint
  .custom instance void [mscorlib]System.STAThreadAttribute::.ctor() = ( 01 00 00 00 ) 
  // Code size       23 (0x17)
  .maxstack  2
  .locals init ([0] bool x,
           [1] bool V_1)
  IL_0000:  nop
  IL_0001:  ldloc.0
  IL_0002:  ldc.i4.0
  IL_0003:  ceq
  IL_0005:  stloc.1
  IL_0006:  ldloc.1
  IL_0007:  brfalse.s  IL_0015
  IL_0009:  ldstr      "hello world"
  IL_000e:  call       void [mscorlib]System.Console::WriteLine(string)
  IL_0013:  nop
  IL_0014:  nop
  IL_0015:  nop
  IL_0016:  ret
} // end of method Module1::Main

推荐阅读