gpt4 book ai didi

c# - Array#Contain 与 OR 逻辑与 switch 语句的性能

转载 作者:行者123 更新时间:2023-12-05 07:59:04 24 4
gpt4 key购买 nike

哪个最快,哪个最慢 (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 翻译成下面的汇编器等价物:

  1. Array.Contains 方法

    lea    EDI, [...]
    mov ECX, sizeof(...)
    repne scasd
  2. if 语句中的顺序 OR

    mov    EAX, ...
    cmp EAX, 0
    jz iftrue
    cmp EAX, 1
    jz iftrue
    cmp EAX, 3
    jz iftrue
    ...
    jmp endif
    iftrue:
    ...
    endif:
  3. 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com