Reputation: 3074
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
.
Upvotes: 3
Views: 686
Reputation: 14973
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.
Upvotes: 10
Reputation: 52538
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.
Upvotes: 3
Reputation: 59496
I believe this check
if num != 4 { ... }
if faster than an assignment
num = 4
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
}
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
Upvotes: 0