简体   繁体   English

Java 中 x + x 和 2*x 的区别

[英]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.

相关问题 java中的x++和++x有区别吗? - Is there a difference between x++ and ++x in java? 如果我分配“double x = 2.3”,java中的“int x =(int)x”和“x =(int)x”有什么区别? - What is the difference between "int x = (int) x" and "x = (int) x" in java if I assign "double x = 2.3"? BiFunction 的区别<X, X>和 BinaryOperator<X> - Difference between BiFunction<X, X> and BinaryOperator<X> Java中while(x = false)和while(!x)之间有什么区别? - What is the difference between while (x = false) and while (!x) in Java? Java 中的 `x &gt; 0` 和 `x &gt; 0.0D` 有什么区别吗? - Is there any difference between `x > 0` and `x > 0.0D` in Java? Java Matcher组:理解“(?:X | Y)”和“(?:X)|(?:Y)”之间的区别 - Java Matcher groups: Understanding The difference between “(?:X|Y)” and “(?:X)|(?:Y)” x.toString() 和 x+&quot;&quot; 的区别 - Difference between x.toString() and x+"" “Object [] x”和“Object x []”之间有什么区别吗? - Is there any difference between “Object[] x” and “Object x[]”? 0x0A 和 0x0D 的区别 - Difference between 0x0A and 0x0D Java:格式说明符%x和%h之间有什么区别? - Java: What's the difference between format specifiers %x and %h?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM