U
U
Urukhayy2014-10-24 10:49:12
Programming
Urukhayy, 2014-10-24 10:49:12

Which check is faster?

if(variable >= 300)
vs
if(variable > 299)
and
if(variable != 200)
vs
if(variable < 200)

Answer the question

In order to leave comments, you need to log in

5 answer(s)
S
Sergey, 2014-10-24
@Urukhayy

Which check is faster?

Which triggers the branch predicted by the branch predictor (because the branch that the code will take will go into the pipeline)
If in the context of PHP / Python / Ruby, then there is no difference at all, because the command stream is formed as it is executed and in the end it will not really turn out to resolve something like that, and then it doesn’t matter which of the listed conditions you will fulfill. And if we talk about java/javascript/c#/c++/etc, then it matters more how often one or the other code branch will work. Let's say if the condition is always met or not met, then after the first two iterations a modern processor will always guess which branch of the code will be loaded and there will be no overhead at all. I don’t know how on AMD, but on Intel, the prediction that the branches will be executed alternately works just as well, once one, another time another.
So it does not matter at all what will be executed in the condition. It is important that it be predictable, succumb to some patterns. And then it will be as productive as possible. And the comparison operation itself is one operation. and it doesn't matter what kind of operation it will be. It is much more important that the entire stream of commands that goes to execution be in the processor cache.
And yes, if this is a one-time condition at all, then you can just score. This is only important in cycles.

X
xmoonlight, 2014-10-24
@xmoonlight

no difference, because a mathematical comparison operation is one processor instruction.

M
MilkyWay, 2014-10-24
@MilkyWay

even on the weakest computers there is no difference in the speed of these checks

S
svd71, 2014-10-24
@svd71

in the interpreter they work faster with one character, in the compiler there is no difference: there are single processor instructions for this type of setting operation.

S
SilentFl, 2014-10-24
@SilentFl

It all depends on the compiler used, and the specified settings. For example, the compiler can
expand the line into

add eax, 5  //в eax - переменная v
cmp eax, 200
jl label1

and maybe in
add eax, 5
jge short label1

the difference is quite noticeable: in the second variant, a conditional transition immediately takes place (that is, we know that ZF has already been set by the previous operation), and it is short, which also gives a small increase in speed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question