Sunday Sep 21, 2008

Java - Instruction set rather than time

One guy asked a question on a Java Forum: which operation is faster - post-increment or pre-increment. I really don't feel these things make a big difference in code performance. I have written a small code to check what nanosecond API of Java is telling about it. And again I reached to a wrong benchmarking. 

class InstructionCheck {
    private int x = 0;
 
    public void countup_() {
        ++x;
    }
    public void countup() {
        x++;
    }
    public void countdown() {
        x--;
    }
    public void count2up() {
        x = x+2;
    }
    public void count2down() {
        x = x-2;
    }
    public static void main(String[] args) {
        long stime = 0;
        long etime = 0;
        InstructionCheck ic = new InstructionCheck();

        stime = System.nanoTime();
        ic.countup_();
        System.out.println(System.nanoTime() - stime);

        stime = System.nanoTime();
        ic.countup();
        System.out.println(System.nanoTime() - stime);

        stime = System.nanoTime();
        ic.countdown();
        System.out.println(System.nanoTime() - stime);

        stime = System.nanoTime();
        ic.count2up();
        System.out.println(System.nanoTime() - stime);

        stime = System.nanoTime();
        ic.count2down();        
        System.out.println(System.nanoTime() - stime);
    }
}         

And the output after several run: 

20952
5308
5587
5587
5308

Now, no doubt the first value is not correct, because of some other reason(I really don't know why) but may be some reigster setting, first time using the class or something else.

But if we see the assemble code, it will simple say that there is(should) no difference in ++i or i++. Look at this :

public void countup_();
  Code:
   0:   aload_0
   1:   dup
   2:   getfield        #2; //Field x:I
   5:   iconst_1
   6:   iadd
   7:   putfield        #2; //Field x:I
   10:  return

public void countup();
  Code:
   0:   aload_0
   1:   dup
   2:   getfield        #2; //Field x:I
   5:   iconst_1
   6:   iadd
   7:   putfield        #2; //Field x:I
   10:  return

The complete assemble code, you can see by option javap -c FileName. My personal opinion is to check the instruction set rather checking the time by nanosecond or millisecond because some benchmarking issue can lead to a different result(which can be completely wrong, like in our case). Here we can easily see that ++i and i++ leads to same instruction and hence both will be more or less equal in performace.

About

Hi, I am Vaibhav Choudhary working in Sun. This blog is all about simple concept of Java and JavaFX.

Search

Archives
« July 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
  
       
Today