问题
An example of thee shorthand Java Arithmetic operator is a += 4;
for a=a+4;
In The Complete Reference, Java 2, Herbert Schildt mentions "they are implemented more efficiently by the Java run-time system than are their equivalent"
What makes its implementation more efficient than a=a+4;
回答1:
Only microbenchmarks can confirm or reject the author's claim in any given execution environment.
On a modern JVM, it is more likely than not that the two versions will exhibit identical performance.
P.S. If the "2" in the book title is as in "Java 2", I'd strongly recommend getting a more up-to-date book!
回答2:
For a += 4
javac
can produce IIC instruction which does Increment local variable by constant. It is theoretically more efficient then IADD.
IADD
does Add int with popping up two values from stack then pushing back the result.
IIC
does nothing on stack but increments local variable.
So if you may work on a very limited and primitive JVM
like you may found on a Java Card this may matter but in %99.9 of the scenarios it does not. Java, JVM and most other virtual machines came a long way.
Btw which edition of the book, do you use? Amazon mentions it will have a 9th version in 2014. It would surprise me if that line is still in the book.
回答3:
As with the unary increment operator (++
) both versions are identical concerning performance as the same bytecode is generated out of them (at least using the Eclipse JDT).
回答4:
a+=4 : it gives implicit type conversion. for example consider a+=4.4 it automatically coverts 4.4 to 4. but a = a+4.4 give you casting error.
来源:https://stackoverflow.com/questions/19957085/why-are-arithmetic-assignment-operators-more-efficient