如何在HotSpot JVM中实现模运算符? [英] How is the modulo operator implemented in the HotSpot JVM?

查看:164
本文介绍了如何在HotSpot JVM中实现模运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,模数操作可以使用小 & 明智的魔法,其中除数是2的幂...

I understand that the modulus operation can be optimised using a little & wise magic where the divisor is a power of 2...


  • 并且可能这是JIT编译器的优化?

推荐答案

是的,模数 x%pow(2,n)可以使用 x& ((1<< n) - 1)

但是如果x为负数,则java中的%-operator可以给出不同的结果,所以盲目地用一个代替另一个可能会破坏代码。

But the %-operator in java can give different results if x is negative, so blindly substituting one for the other can break code.

当位寻址,屏蔽等通常使用& -variant时,因为它在语义上更接近于汇编程序/ C和签名中使用的通常不需要/关心那个案例。

When bit-addressing, masking etc. the &-variant is commonly used, as its semantically closer to what is used in assembler/C and signedness is usually not wanted/cared about in that case.

至于如果JIT将%优化为&,答案是:它完全取决于JIT - 那就是一个移动的目标。

As for if the JIT optimizes % to &, the answer is: it depends entirely on the JIT - and thats a moving target.

如果 x%y 其中y不是常数,如果y是幂,则很难检测到2,所以大概是这种情况不可优化,因为检测它是非常困难或不可能的。如果y是常数,则JIT仍然证明x不是负数 - 或者插入类似于的条件结果= x< 0? x%y:x& (Y-1)。它可能会也可能不会,这取决于所讨论的JIT,也取决于平台。至少Hotspot在某些情况下对不同的处理器(同一个ISA,即AMD vs Intel)使用不同的优化。

In case x % y where y isn't a constant its pretty difficult to detect if y is a power of 2, so presumably that case isn't optimizable because detecting it is very difficult or impossible. If y is a constant, the JIT still has prove that x isn't negative - or insert a conditional similar to result = x < 0 ? x % y : x & (y-1). It may or may not do so, depending on JIT in question and also depending on the platform. At least Hotspot is known to use different optimizations for different processors (of the same ISA, namely AMD vs Intel) in some cases.

这篇关于如何在HotSpot JVM中实现模运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆