First of all, the Java language specification says nothing about timing. But assuming we use a typical compiler such as Suns javac, we see that all of the above examples ( a++ , ++a , a += 1 , a = a + 1 ) can be compiled into something like:
iinc instruction working with variables:
iload_<variable> iinc <variable>, 1 istore_<variable>
iadd instack using stack (here variable 1 is used as storage):
iload_1 iconst_1 iadd istore_1
It is up to the compiler to choose the best way to compile them. For example. there is no difference between them. And there should be no difference between statements - they all express the same thing: adding one to a number.
Be that as it may, the iinc and iadd can be compiled using JIT for something fast and platform dependent, and in the end I would suggest that the normal runtime compiles both versions into the same assembler code.
With my compiler * jdk1.6.0_20 * the "increment" methods even use the same instruction.
public class Test { public static void main(String[] args) { int a = 0; a = a + 1; a += 1; a++; ++a; } }
This is a parsing:
Compiled from "Test.java" public class Test extends java.lang.Object{ public Test(); Code: 0: aload_0 1: invokespecial
dacwe
source share