英文:
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 < b + b) {
...
}
Instead of
if (a < 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论