作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
哪个最快,哪个最慢 (C#)?
// Array#Contain
int i = ...;
if ((new int[] { 0, 1, 3, 7, ... }).Contains(i))
{
...
}
// OR logic
int i = ...;
if (i == 0 || i == 1 || i == 3 || i == 7 || ...)
{
...
}
// switch statement
int i = ...;
switch(i)
{
case 0:
case 1:
case 3:
case 7:
...
...
break;
}
最佳答案
这些东西的性能取决于目标机器架构,也许还有操作系统。
对于 x86/x64 机器,我相信上面的代码应该由 JIT 翻译成下面的汇编器等价物:
Array.Contains
方法
lea EDI, [...]
mov ECX, sizeof(...)
repne scasd
if
语句中的顺序 OR
mov EAX, ...
cmp EAX, 0
jz iftrue
cmp EAX, 1
jz iftrue
cmp EAX, 3
jz iftrue
...
jmp endif
iftrue:
...
endif:
switch
语句
lea EBX, [case_values_table]
xor EAX, EAX
mov AL, case_index
xlat
mov ESI, EAX
jmp [case_codeblocks_table][ESI * 4 or 8]
您唯一需要做的就是对每个选项的 ASM 指令计时求和,包括由于清除操作码的正概率而导致的任何 jmp
的潜在劣势预取队列。
但我相信,更好的建议是选择最受支持的 C# 代码。
关于c# - Array#Contain 与 OR 逻辑与 switch 语句的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23262847/
我是一名优秀的程序员,十分优秀!