0

Is there in JAVA a performance difference between i++; and i--;

I'm not able to evaluate bytecode for this, and I think that simple benchmarks are not reliable because of dependence on a specific algorithm.

Joseph Quinsey
  • 9,553
  • 10
  • 54
  • 77
Francesco Bianco
  • 519
  • 1
  • 5
  • 12

2 Answers2

1

im not able to evaluate bytecode

Besides the duplicate which I linked and which shows some general things to consider when asking performance related questions:

Given the following sample code (System.err.println is essentially necessary so that the compiler does not optimize away the unused variable):

public class IncDec {
   public static void main(String[] args) {
        int i = 5;

        i++;
        System.err.println(i);
        i--;
        System.err.println(i);
    }
}

Disassembled code:

> javap -c IncDec
Compiled from "IncDec.java"
public class IncDec {
  public IncDec();
    Code:
       0: aload_0
       1: invokespecial #8                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: iconst_5
       1: istore_1                          // int i = 5

       2: iinc          1, 1                // i++

       5: getstatic     #16                 // Field java/lang/System.err:Ljava/io/PrintStream;
       8: iload_1
       9: invokevirtual #22                 // Method java/io/PrintStream.println:(I)V

      12: iinc          1, -1               // i--

      15: getstatic     #16                 // Field java/lang/System.err:Ljava/io/PrintStream;
      18: iload_1
      19: invokevirtual #22                 // Method java/io/PrintStream.println:(I)V

      22: return
}

So, no, there is no performance difference in this particular case on a bytecode level - both statements are compiled to the same bytecode instruction.

The JIT compiler could be free to do any additional optimization though.

Andreas Fester
  • 36,091
  • 7
  • 95
  • 123
0

In Java, there isn't a difference in speed between the two. At the most basic level, subtraction is simply addition. That is, taking the 2's complement and adding it.

A Osman
  • 171
  • 2
  • 8