简体   繁体   中英

Assignment vs if not equal to then assign… Swift being the language I care most about

I have some code that will get ran every so often. As far as performance goes, is there any difference between the following to satements, and if so, which one is faster?

num = 4

vs

if num != 4 {
    num = 4
}

I understand the difference is probably minimal, but I have had this question run through my mind on occasion. Also I would be interested in the closely related questions to this that might use a Bool or String instead of an Int .

The first one is faster for sure, because the processor has to do 1 instruction, which takes 1 clock cycle. In the second one there is at least 1 instruction or more (Comparison and optional assignment).

Assuming we have this code:

var x = 0
x = 4

Here are the important lines of the assembly ( swiftc -emit-assembly ):

    movq    $0, __Tv4test3numSi(%rip)  // Assigns 0 to the variable
    movq    $4, __Tv4test3numSi(%rip)  // Assigns 4 to the variable

As you can see, a single instruction is needed

And with this code:

var x = 0
if x != 4 {
    x = 4
}

Assembly:

    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)

As you can see, the second one uses either 3 instructions (when already equal to 4) or 4 instructions (when not equal 4).

It was clear to me from the beginning, but the assembly nicely demonstrates that the second one can't be faster.

It's faster for me to read "num = 4". About three times faster. That's what I care about. You are attempting a microoptimisation of very dubious value, so I would be really worried if I saw someone writing that kind of code.

I believe this check

if num != 4 { ... }

if faster than an assignment

num = 4

Scenario #1

So if most of the times num is equals to 4 you should skip the useless assignment and use this code

if num != 4 {
    num = 4
}

Scenario #2

On the other hand if most of the times num is different from 4 you could remove the check and juts go with the assignment

num = 4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM