shallowinggg
shallowinggg

Reputation: 51

When exec (i / j) and (i % j), jvm will do one calc or two?

I used javap command to make bytecodes, and there are two instructions: idiv and irem.I know that div's result store in different register, will jvm only exec div opeartion once?

int i = 10;
int a = i / 4;
int b = i % 4;

bytecode:

Code:
      stack=2, locals=4, args_size=1
         0: bipush        10
         2: istore_1
         3: iload_1
         4: iconst_4
         5: idiv
         6: istore_2
         7: iload_1
         8: iconst_4
         9: irem
        10: istore_3
        11: return

Upvotes: 1

Views: 96

Answers (1)

Stephen C
Stephen C

Reputation: 719336

If you were interpreting byte codes, the JVM would treat the idiv and irem as separate (bytecode) instructions and execute them separately.

If you are talking about code that has been compiled to native code, it will depend on:

  • whether there is a native instruction on your execution platform that combines division and remainder1, and
  • whether the JIT compiler makes use of the capability of that instruction.

You can use the -XX+PrintAssembly option to check what the JIT compiler generates. (You also need to supply -XX:UnlockDiagnosticVMOptions: see the java manual entry.)

Note that the answer is liable to be hardware and Java version dependent.


1 - The 32 and 64 bit IDIV instructions for x86 and x86-64 do.

Upvotes: 2

Related Questions