Which is faster 5 + 5 + 5 + 5 + 5 or 5 * 5?

I don’t know how to ask, but just want to ask. Help me tag it, please. Anyway, my friend asked me a question which one is faster in Java

int a = 5 + 5 + 5 + 5 + 5

or

int b = 5 * 5 ?

Is he language dependent? I mean, afaster than bin java but not in C

my answer is afaster than bcomparing addition / multiplication in a computer organization

+3
source share
8 answers

It depends on the platform (and the compiler). If you need to know, then measure it. It is unlikely that you will find yourself in a situation where you need to know.

( ); ., , http://en.wikipedia.org/wiki/Constant_folding.

+14

. :

public class Toto {
    public static void main(String[] args) {
        int a = 5 + 5 + 5 + 5 + 5;
        int b = 5 * 5;
    }
}

:

public class Toto
{
    public static void main(String args[])
    {
        byte byte0 = 25;
        byte byte1 = 25;
    }
}

.

+13

,

int a = 25;
int b = 25;

( 100% , , ).

, , JIT, 1:1 , , , ( , , : 1 3 , - ).

, , , ( 1 , , 4 ).

, , , (5<<2+5).

+6

: , . ( , Java-to-bytecode, JIT).

-, "" . , , . , , . , , , X86 . "" , . , , , , . , , " ", .

, Hotspot 32- Pentium ( Intel, , , , , ). , : , ; .

, , , , 2 , JIT- . , , x 1/x, x - 2.

, , Java, JIT- , , . , , , "5 + 5 + 5 + 5 + 5", Java "25".

+4

. f1(n) = n * c, f2(n) = Sum[1->n] c.

- O(1) ( , n), O(n) ( , n).

+1

, :

  • ? , .

  • ? , NOP ( ).

  • ? , , , () , add-operation

  • .

, , , , .

, , , , : . A B, , // , , , .

+1

, , , .

, .

0

I assume that Addition is faster than multiplication, because (as far as I know) all multiplications are considered as additions

Added:

read here for some explanation

-1
source

Source: https://habr.com/ru/post/1786892/


All Articles