分配vs如果不等于那么分配... Swift是我最关心的语言

Set*_*hmr 2 performance if-statement variable-assignment swift

我有一些代码会经常运行.就性能而言,以下与声明之间是否有任何区别,如果是,哪一个更快?

num = 4
Run Code Online (Sandbox Code Playgroud)

VS

if num != 4 {
    num = 4
}
Run Code Online (Sandbox Code Playgroud)

我知道差异可能很小,但我偶尔也会想到这个问题.此外,我会对与此密切相关的问题感兴趣,这些问题可能使用BoolString代替Int.

Kam*_*xom 8

第一个肯定是更快,因为处理器必须做1条指令,这需要1个时钟周期.在第二个中至少有1个指令或更多(比较和可选的分配).

假设我们有这个代码:

var x = 0
x = 4
Run Code Online (Sandbox Code Playgroud)

以下是assembly(swiftc -emit-assembly)的重要部分:

    movq    $0, __Tv4test3numSi(%rip)  // Assigns 0 to the variable
    movq    $4, __Tv4test3numSi(%rip)  // Assigns 4 to the variable
Run Code Online (Sandbox Code Playgroud)

如您所见,需要一条指令

并使用此代码:

var x = 0
if x != 4 {
    x = 4
}
Run Code Online (Sandbox Code Playgroud)

部件:

    movq    $0, __Tv4test3numSi(%rip) // Assign 0 to the variable
    cmpq    $4, __Tv4test3numSi(%rip) // Compare variable with 4
    je  LBB0_4                        // If comparison was equal, jump to LBB0_4
    movq    $4, __Tv4test3numSi(%rip) // Otherwise set variable to 4
LBB0_4:
    xorl    %eax, %eax                // Zeroes the eax register (standard for every label)
Run Code Online (Sandbox Code Playgroud)

如您所见,第二个使用3个指令(当已经等于4时)或4个指令(当不等于4时).

我从一开始就很清楚,但是大会很好地证明了第二个不能更快.