Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficency of Comparisons in C++? ( abs(X)>1 vs abs(x) != 0)

I know- Premature optimization.
But I've got code that's supposed to find out if a position is changed vs a cached position.

Current code is:

if(abs(newpos-oldpos) > 1){
    .....
}

Is it more efficient to use the following?

if(abs(newpos-oldpos) != 0){
    ....
}

Why or why not? I'm currently debating it my head which is more readable and was wondering if there was a performance difference I was missing.

like image 390
Luciano Avatar asked Nov 26 '22 23:11

Luciano


1 Answers

Why not this?

if (newpos != oldpos) {
    ...
}

More efficient than both due to the lack of abs(), and clearer to boot.

like image 168
Noah Medling Avatar answered Dec 13 '22 19:12

Noah Medling