vb.net - 在 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
我经常想知道一种方法是否比另一种更快?我在互联网上搜索过,但没有找到这两种方法的任何比较。我倾向于使用第一个示例,因为我认为它更易于阅读,但如果有人有证据表明第二种方法更快,我会很感兴趣。通常,这些嵌入在可能迭代数千次的循环中,所以我认为在这种情况下我会将性能置于易读性之上。
解决方案
这些通过 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
推荐阅读
- swift - 如何在 Xcode 10 的 Scene Kit 中为材质添加色调
- sql - MS SQL Server:引用存储在表中的 WHERE 语句?
- php - httpd / roundcube 抛出 500 个零错误,打印到客户端或在日志中生成
- spring - 微服务中审计日志(用户活动)的最佳实践是什么?
- firebase - 我如何使用云功能注册 Firebase?
- javascript - 在 Keystonejs 部分视图中使用预定义的模型数据
- java - 使用 API 将大文件上传到 JackRabbit 存储库
- javascript - 文本字符串必须在
React Native 中的组件问题 - algorithm - 生成有序约束集
- javascript - 使单词出现在屏幕随机位置的 JavaScript/JQuery 代码不起作用