在Java中,x + x 和 2*x 之间的区别是什么。

huangapple go评论80阅读模式
英文:

Difference between x + x and 2*x in Java

问题

我正在阅读关于LeetCode问题的答案:https://leetcode.com/problems/divide-two-integers/。这个问题要求不使用乘法。在阅读了一些答案后,我不知何故产生了这样一个错误观念,即x+x从内存使用和避免类型溢出的角度来看优于2*x。在发布了问题之后,我找不到任何支持这种说法的证据。请忽略这个问题。

我看到在Java中有一个常见的做法是使用x + x,而不是2*x,尤其是对于整数。例如:

int x = 1;
x += x;

而不是

int x = 1;
x = 2*x;

使用

if (a < b + b) {
  ...
}

而不是

if (a < 2*b) {
  ...
}

x + x 相对于 2*x 能节省一点点内存吗?

英文:

I was reading the answers to a Leetcode problem: https://leetcode.com/problems/divide-two-integers/. This problem requires not using multiplication. After reading a few answers, I somehow had a misconception that x+x is better than 2*x in terms of memory and avoiding type overflow. After post the question, I cannot find any evidence to support this statement. Please ignore this question.


I saw a common practice in Java is using x + x instead of 2*x especially for int. For example

int x = 1;
x += x;

Instead of

int x = 1;
x = 2*x;

Using

if (a &lt; b + b) {
  ...
}

Instead of

if (a &lt; 2*b) {
  ...
}

Does x + x save slightly more memory than 2*x?

答案1

得分: 2

似乎更像是一种习惯,而不是有任何理由使用这种约定,除非 JVM 在进行 + 运算时比 * 更高效,而这可能是我们完全可以忽略的事情。

英文:

It seems more like a habit than has any reason to use this convention, unless JVM is more efficient in carrying our + operation than *, which probably is something we can totally ignore

huangapple
  • 本文由 发表于 2020年5月31日 05:23:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/62108827.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定