It's always a good idea to profile and test, but Math.log
is much more expensive than either -
or /
, so Math.log(a/b)
(which calls Math.log
only once) will, in principle, be faster than Math.log(a) - Math.log(b)
(which calls it twice).
Could the way I calculate value
have an impact on performance (Assume this gets called very often) or does the Java compiler optimize this for me?
The compiler can't optimize that, no, because the two expressions are not equivalent. (Mathematically, it's true that ln a/b = ln a − ln b, but that's not necessarily true of floating-point numbers, since they are imprecise. And of course, Math.log(-1) - Math.log(-1)
is NaN
, making it quite different from Math.log(-1 / -1)
.)
That said . . . you really need to test. Even if this gets called a lot, the difference between the two expressions will probably turn out to be negligible compared to (say) the cost of a nearby println
that gets called almost as often. Your program would really have to run this expression an extraordinary number of times per second before you'd expect to observe a difference.