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 fortran for which one is faster 5+5+5+5+5 or 5*5?

$
0
0

Both are constant expressions, so they will be simplified to

int a = 25;int b = 25;

at compile time (100% sure, even toy compilers do this, as it is one of the simplest optimisations possible).

In the remote case those operations are not simplified, assuming that there is a JIT that maps the multiplication and add opcodes in a 1:1 relationship to their CPU instruction counterparts, in most modern architectures all integer arithmetic operations usually take the same number of cycles, so it will be faster multiply once than add four times (just checked it, addition is still slightly faster than multiplication: 1 clock vs 3 clocks, so it still pays using a multiplication here).

Even in a super-scalar architecture, where more than one instruction can be emitted per cycle, the chain of add operations has a data dependency, so they will have to execute sequentially (and as the add instruction is just 1 cycle, there's no possible pipeline overlapping, it will still take 4 cycles).

In most CPU architectures, the optimal instruction sequence will probably be a shift of two positions to the left and then adding the original value (5<<2+5).


Viewing all articles
Browse latest Browse all 9

Trending Articles



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