在写代码的时候,常常使用if-else显得很麻烦,对于简单的赋值操作,我们可以使用三目运算符,但是与if-else比较的效率呢,不知道有没有人关注过。
现在来看看下面的测试:
public class Test1{
public static void main(String[] argv){
boolean b = true;
if(b){
b = false;
}else{
b = true;
}
}
}
public class Test2{
public static void main(String[] argv){
boolean b = true;
b = (b==true?false:true);
}
}
进行javap分析:
D:>javap -s Test1
Compiled from "Test1.java"
public class Test1 extends java.lang.Object{
public Test1();
Signature: ()V
public static void main(java.lang.String[]);
Signature: ([Ljava/lang/String;)V
}
D:>javap -s Test2
Compiled from "Test2.java"
public class Test2 extends java.lang.Object{
public Test2();
Signature: ()V
public static void main(java.lang.String[]);
Signature: ([Ljava/lang/String;)V
public class Test2{
public static void main(String[] argv){
boolean b = true;
b = (b ? false : true);
}
} }
D:>javap -c Test1
Compiled from "Test1.java"
public class Test1 extends java.lang.Object{
public Test1();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_1
1: istore_1
2: iload_1
3: ifeq
11
6: iconst_0
7: istore_1
8: goto 13
11: iconst_1
12: istore_1
13: return
}
D:>javap -c Test2
Compiled from "Test2.java"
public class Test2 extends java.lang.Object{
public Test2();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_1
1: istore_1
2: iload_1
3: iconst_1
4: if_icmpne
11
7: iconst_0
8: goto 12
11: iconst_1
12: istore_1
13: return
}
可见,进行的存储结构都相同,并且执行的指令条数也相同,只是执行过程中处理出现了一条语句的差异:
ifq还是if_icmpne,对于这两个,应该决定着效率问题,但是谁的更好呢?
增加:
根据下面回复的问题,确实有此种情况出现:
将Test2代码变化为:
public class Test2{
public static void main(String[] argv){
boolean b = true;
b = (b ? false : true);
}
}
则相应的javap分析变为:
D:>javap -c Test2
Compiled from "Test2.java"
public class Test2 extends java.lang.Object{
public Test2();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_1
1: istore_1
2: iload_1
3: ifeq 10
6: iconst_0
7: goto 11
10: iconst_1
11: istore_1
12: return
}
与Test1的比较得出:
D:>javap -c Test1
Compiled from "Test1.java"
public class Test1 extends java.lang.Object{
public Test1();
Code:
0: aload_0
1: invokespecial #1; //Method java/lang/Object."<init>":()V
4: return
public static void main(java.lang.String[]);
Code:
0: iconst_1
1: istore_1
2: iload_1
3: ifeq 11
6: iconst_0
7: istore_1
8: goto 13
11: iconst_1
12: istore_1
13: return
}
解析过程中少解析了一条指令,但是执行的代码条数相同。
也就是说,这样的写法不会提高任何效率,但是Test2.java代码相对简洁一些。
查看了一下class文件,分别为315字节(Test1.class)和307字节(Test2.class),去除命名差异引起的字节变化,大概也就是多出来的那条指令所引起的。
OK??