[英]Difference between x + x and 2*x in Java
I was reading the answers to a Leetcode problem: https://leetcode.com/problems/divide-two-integers/ .我正在阅读 Leetcode 问题的答案: 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.在阅读了一些答案之后,我不知何故有一个误解,即
x+x
在 memory 和避免类型溢出方面优于2*x
。 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.我在 Java 中看到一个常见的做法是使用 x + x 而不是 2*x,尤其是对于 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
? x + x
是否比2*x
节省更多 memory ?
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这似乎更像是一种习惯,而不是任何理由使用此约定,除非 JVM 在执行我们的 + 操作方面比 * 更有效,这可能是我们完全可以忽略的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.