Recently
there was a question whether ++j is better than j++ in
terms of performance. Typically this suggestion is applicable for C++
programming.
In below
java code, let’s assume a value of 10 is passed as input to both the functions.
After executing the line, in func1() the value of k will be 10 whereas
value of j will be 11 and in func2(), the value of both k, j
will be 11.
In
C++, in order to return a value of 10 for variable k in func1(), the
value of j is copied to a temp location, j is incremented and
then the value of temp location is returned to k. For func2() this temp
location is not necessary and hence one instruction is less for ++j when
compared to j++.
Code
|
Java
byte code
|
package
com.test;
public
class Test {
public static void func1(int j) {
int k = j++;
}
public static void func2(int j) {
int k = ++j;
}
}
|
public
class com.test.Test extends java.lang.Object{
public
com.test.Test();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public
static void func1(int);
Code:
0: iload_0
1: iinc 0, 1
4: istore_1
5: return
public
static void func2(int);
Code:
0: iinc 0, 1
3: iload_0
4: istore_1
5: return
}
|
To verify this in java, let’s examine the byte code and how this is handled.
func1():
The passed input is stored on to the stack using iload and using iinc the value
of j is incremented (so j= 11 now) and k is populated with
value on the stack (which is 10) using istore
func2():
First the value of j is incremented using iinc instruction and then
incremented value is stored on to stack (which is 11) and then the same is
returned to k using iload and istore respectively.
Hence the number of instructions is same in both the cases.
Now if the argument is that if no assignment is required then is ++j better? Let’s write a simple code and examine its byte code as shown in the below table:
Now if the argument is that if no assignment is required then is ++j better? Let’s write a simple code and examine its byte code as shown in the below table:
Code
|
Java
byte code
|
package com.test;
public class Test {
public static void func1(int j) {
j++;
}
public static void func2(int j) {
++j;
}
}
|
public class com.test.Test extends
java.lang.Object{
public com.test.Test();
Code:
0: aload_0
1:
invokespecial #1; //Method
java/lang/Object."<init>":()V
4: return
public static void func1(int);
Code:
0:
iinc 0, 1
3: return
public static void func2(int);
Code:
0:
iinc 0, 1
3: return
}
|
Compiler is smart to understand that the variable needs to
be incremented irrespective of its position.
So what’s the conclusion? In case of java the number of
instructions is same for the both the cases and hence we are free to choose our
option while coding :-)
