Java – simple if statement and normal if statement

At the Java bytecode level, is there any difference between a 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 problem is that I see something like Java in the "high performance" class awt. Rectangle and point have only variants without curly braces

Is there any speed advantage, or is it just code style?

Solution

In addition to the maintainability of the code, it is also exactly the same in terms of performance You will not speed up by deleting {} because {} is not your own instruction

I use {} normally because it makes the code easy to read (IMO) and is not conducive to 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");
    }

Generated bytecode:

// 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,same]

As you can see, it's the same

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>