while(true)和for(;;)分析

由字节码看,两者一致。

1
2
3
4
5
6
7
8
9
10
11
12
13
public class WhileForTest {
public void forFunc() {
for (;;) {
System.out.println("for loop");
}
}

public void whileFunc() {
while (true) {
System.out.println("while loop");
}
}
}
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
32
33
34
35
36
37
38
39
40
41
42
43
44
public class jmh/WhileForTest {

// compiled from: WhileForTest.java

// access flags 0x1
public <init>()V
L0
LINENUMBER 7 L0
ALOAD 0
INVOKESPECIAL java/lang/Object.<init> ()V
RETURN
L1
LOCALVARIABLE this Ljmh/WhileForTest; L0 L1 0
MAXSTACK = 1
MAXLOCALS = 1

// access flags 0x1
public forFunc()V
L0
LINENUMBER 10 L0
FRAME SAME
GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
LDC "for loop"
INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/String;)V
GOTO L0
L1
LOCALVARIABLE this Ljmh/WhileForTest; L0 L1 0
MAXSTACK = 2
MAXLOCALS = 1

// access flags 0x1
public whileFunc()V
L0
LINENUMBER 16 L0
FRAME SAME
GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
LDC "while loop"
INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/String;)V
GOTO L0
L1
LOCALVARIABLE this Ljmh/WhileForTest; L0 L1 0
MAXSTACK = 2
MAXLOCALS = 1
}

评论