Does java have a divmod instruction?

5.4k Views Asked by At

Besides divmod being a native instruction on many chipsets, it also is a lot easier on the eyes when subdividing a number in multiple different denominations

(which happens with e.g. milliseconds -> datetime conversion, or cents -> coin denomination conversion).

So is there a divmod that returns both the result of the division and of the remainder at the same time?

2

There are 2 best solutions below

0
On BEST ANSWER

The HotSpot JIT compiler will replace division and modulo operations against the same arguments with a single divmod operation, if supported. So while this may not address the readability concerns, you don't need to worry about performance.

From the OpenJDK 9 source code:

  case Op_ModI:
    if (UseDivMod) {
      // Check if a%b and a/b both exist
      Node* d = n->find_similar(Op_DivI);
      if (d) {
        // Replace them with a fused divmod if supported
        if (Matcher::has_match_rule(Op_DivModI)) {
          DivModINode* divmod = DivModINode::make(n);
          d->subsume_by(divmod->div_proj(), this);
          n->subsume_by(divmod->mod_proj(), this);
        } else {
          // replace a%b with a-((a/b)*b)
          Node* mult = new MulINode(d, d->in(2));
          Node* sub  = new SubINode(d->in(1), mult);
          n->subsume_by(sub, this);
        }
      }
    }
    break;

By using diagnostic options to print the generated JIT instructions, I was able to see that a method that used both idiv and irem instructions at the C1 optimization level used only a single idiv instruction at the C2 level.

4
On

Java has this implemented for BigInteger or BigDecimal. These are meant for really huge integers and decimal numbers, rather than extreme efficiency.

Low level optimization is not the strength of Java, so I'd recommend opting out from Java. You can make the algorithm in C or even use Assembler. Then, if you need to use it in a Java application, you can always make it a library. Then, with Java Native Interface, you can use the library within your app.