除了 divmod
是许多芯片组上的 native 指令之外,在将数字分割为多个不同面额时,它也更容易在眼睛上显示
(发生在例如毫秒 -> 日期时间转换,或美分 -> 硬币面额转换)。
那么有没有divmod
同时返回除法和余数的结果呢?
最佳答案
如果支持,HotSpot JIT 编译器将用单个 divmod 操作替换针对相同参数的除法和取模操作。因此,虽然这可能无法解决可读性问题,但您无需担心性能。
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;
通过使用 diagnostic options to print the generated JIT instructions ,我能够看到在 C1 优化级别同时使用 idiv
和 irem
指令的方法在C2级。
关于java - java有divmod指令吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46905740/