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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With