Quantcast
Channel: which one is faster 5+5+5+5+5 or 5*5? - Stack Overflow
Viewing all articles
Browse latest Browse all 9

Answer by Neil Coffey for which one is faster 5+5+5+5+5 or 5*5?

$
0
0

There are at least two questions here: the performance of the underlying operations, and what the compiler does. (In fact, what both the Java-to-bytecode compiler and the JIT compiler do.)

Firstly, the question of the "raw" operations. As a general rule, addition, subtraction and multiplication take roughly the same time on a large number of processors. You might imagine that multiplication is a lot slower, but it turns out not to be. Have a look, for example, at this paper giving some experimental timings of X86 instructions on various processors. Multiplication is ever so slightly "slower" overall in that it has a higher latency. What that effectively means is that if the processor was doing nothing but a series of multiplications on different pieces of data, it would be slightly slower than doing a series of additions on different pieces of data. But provided that there are other instructions round about that can be executing "while the multiplication is finishing off", then there ends up not being much difference overall between addition and multiplication.

I also made a list a while ago of the timings of floating point instructions used by Hotspot on a 32-bit Pentium (the figures came originally from Intel's processor manual, and as I recall I did test experimentally that in practice these are the timings you get). Notice that there's a very similar pattern: addition, subtraction and multiplication essentially take the same time as one another; division is notably slower.

Then, if you look at the table on the page I just mentioned, you'll see that divisions by a power of 2 are faster because the JIT compiler can translate these into a multiplication. Powers of two can be represented exactly in floating point representation, so there is no loss of precision if you replace a division by x by a multiplicaiton by 1/x where x is a power of 2.

Or in other words, both the Java compiler and JIT compiler can apply various optimisations which mean that the underlying instructions for a given piece of code aren't necessarily what you think they are. As others have mentioned, one very basic piece of optimisation is to pre-compute values, so that if you write "5+5+5+5+5", in reality the Java compiler should replace this with "25".


Viewing all articles
Browse latest Browse all 9

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>