为什么JDK使用移位而不是乘法/除法? [英] Why does JDK use shifting instead of multiply/divide?

查看:63
本文介绍了为什么JDK使用移位而不是乘法/除法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题:

例如,如果被问到是使用移位还是乘还是除,那么让JVM优化.

If asked whether to use a shift vs a multiply or divide for example the answer would be, let the JVM optimize.

此处的示例: is-shifting-比乘法快

现在我正在查看jdk源,例如

Now I was looking at the jdk source, for example Priority Queue and the code uses only shifting for both multiplication and division (signed and unsigned).

理所当然地认为SO中的帖子是有效的答案,我想知道为什么在jdk中他们更愿意通过轮班做到这一点?

Taking for granted that the post in SO is the valid answer I was wondering why in jdk they prefer to do it by shifting?

这是与性能无关的一些细微细节吗?我怀疑它一定与上溢/下溢乘法和除法有关,但我不确定.

Is it some subtle detail unrelated to performance? I am suspecting it must have something to do with over/underflow multiplication and division but I am not sure.

有人有主意吗?使用移位可以更好地处理巧妙的溢出问题吗?还是只是口味问题?

Anyone has an idea? Are subtly overflow issues handled better using shifting? Or it is just a matter of taste?

推荐答案

我认为在此特定示例中,他们使用符号位来做到这一点. Java缺少无符号类型,因此对于使用最高有效位的数字,无法用a /= 2模拟a >>> 1.请注意,在整个示例中,代码仅使用>>>.我可以肯定地说,这是为了充分利用整个位范围.

I think they do it in this specific example to use the sign bit. Java lacks unsigned types, so it is not possible to emulate a >>> 1 with a /= 2 for numbers that use the most significant bit. Note how the code uses only >>> throughout your example. I am reasonably certain that this is to get full use of the entire bit range.

这篇关于为什么JDK使用移位而不是乘法/除法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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