Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple if statement vs. normal if statement

At Java byte code level, is there any difference between an simple if-statement (Example 1) and a normal if-statement (Example 2):

Example 1:

if (cond) statement;

Example 2:

if (cond) {
    statement;
}

The background of the question, is that I saw in "high performance" classes like java.awt.Rectangle and Point only the variant without curly braces.

Is there any speed benefit, or is that only code style?

like image 714
raceworm Avatar asked Feb 10 '13 20:02

raceworm


2 Answers

Aparte from the maintainability of your code, in terms of performance is exactly the same. You will not gain speed up from removing {}, since {} it is not an instruction by it self.

I normal use with {} because makes the code easy to read (IMO) and less propitious to making errors.

This example:

public void A(int i) {
     if (i > 10) {
        System.out.println("i");
        }
    }

    public void B(int i) {
        if (i > 10)
            System.out.println("i");
    }

byte code generated:

 // Method descriptor #15 (I)V
  // Stack: 2, Locals: 2
  public void A(int i);
     0  iload_1 [i]
     1  bipush 10
     3  if_icmple 14
     6  getstatic java.lang.System.out : java.io.PrintStream [16]
     9  ldc <String "i"> [22]
    11  invokevirtual java.io.PrintStream.println(java.lang.String) : void [24]
    14  return
      Line numbers:
        [pc: 0, line: 5]
        [pc: 6, line: 6]
        [pc: 14, line: 8]
      Local variable table:
        [pc: 0, pc: 15] local: this index: 0 type: program.TestClass
        [pc: 0, pc: 15] local: i index: 1 type: int
      Stack map table: number of frames 1
        [pc: 14, same]

  // Method descriptor #15 (I)V
  // Stack: 2, Locals: 2
  public void B(int i);
     0  iload_1 [i]
     1  bipush 10
     3  if_icmple 14
     6  getstatic java.lang.System.out : java.io.PrintStream [16]
     9  ldc <String "i"> [22]
    11  invokevirtual java.io.PrintStream.println(java.lang.String) : void [24]
    14  return
      Line numbers:
        [pc: 0, line: 11]
        [pc: 6, line: 12]
        [pc: 14, line: 13]
      Local variable table:
        [pc: 0, pc: 15] local: this index: 0 type: program.TestClass
        [pc: 0, pc: 15] local: i index: 1 type: int
      Stack map table: number of frames 1
        [pc: 14, same]

As you can see the are the same.

like image 102
dreamcrash Avatar answered Sep 21 '22 12:09

dreamcrash


The two are exactly the same. The Java compile will produce the same code.

Keep in mind, however, that in the non-bracket case, you will not be able to add multiple sub-statements inside the if-block the way you would be able to in the bracketed case

like image 39
Forhad Ahmed Avatar answered Sep 21 '22 12:09

Forhad Ahmed