Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

which is faster?

I was wondering which of the following would execute faster, just out of curiosity. The language is Java.

int num = -500;
int num2 = 0;

while( Math.abs(num) > num2 )
    num2 ++;

or

int num = -500;
int num2 = 0;
num = Math.abs(num);

while( num > num2 )
    num2 ++;

Essentially I am wondering whether 'Math.abs' is called for every iteration of the while loop, or is there some code optimization going on in the background?

Thanks!

like image 212
Inventor22 Avatar asked Jul 11 '26 22:07

Inventor22


2 Answers

Math.abs() is what is called a pure function, so a really good compiler could theoretically optimize it out. There are functional programming languages specifically designed to do just that, but in Java it would be difficult.

Not only is the second one likely to be compiled into faster code, it's generally accepted as better style, as it makes more clear what actually changes in the loop and what doesn't.

like image 99
Karl Bielefeldt Avatar answered Jul 13 '26 14:07

Karl Bielefeldt


Yes, Math.abs(num) is called for each iteration, because Java can never tell or guess, that a return value only depends on the parameter.

For Java, the method is "equal" to Math.random().

So the first example uses more CPU time.

like image 44
Andreas Dolk Avatar answered Jul 13 '26 13:07

Andreas Dolk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!