面試題:i++和i--哪個快些?
這個不知道是哪位朋友跟我說的一個面試題,當時我聽到這個題目的時候,我也不知所措,或許是對i++和i--的底層實現不知道,也或許沒有關注過這個問題.
今天就在這里做個測試:
1.測試環境:電腦配置: 系統配置:
jdk版本:jdk1.6.0_20
2.測試代碼:
package Sort; public class Increament { /** * @param args * @throws InterruptedException */ public static void main(String[] args) throws InterruptedException { decrement(); increment(); } public static void decrement() { long start2 = System.currentTimeMillis(); for(long i = 100000000L; i > 0; i--) { } long end2 = System.currentTimeMillis() - start2; System.out.println(end2); } public static void increment() { long start = System.currentTimeMillis(); for(long i = 1; i < 100000000L; i ++) { } long end1 = System.currentTimeMillis() - start; System.out.println(end1); } }
3.字節碼
D:\jdk1.6.0_20\bin>javap -c Increament Compiled from "Increament.java" public class Increament extends java.lang.Object{ public Increament(); Code: 0: aload_0 1: invokespecial #1; //Method java/lang/Object."<init>":()V 4: return public static void main(java.lang.String[]) throws java.lang.InterruptedException; Code: 0: invokestatic #2; //Method decrement:()V 3: invokestatic #3; //Method increment:()V 6: return public static void decrement(); Code: 0: invokestatic #4; //Method java/lang/System.currentTimeMillis:()J 3: lstore_0 4: ldc2_w #5; //long 100000000l 7: lstore_2 8: lload_2 9: lconst_0 10: lcmp 11: ifle 21 14: lload_2 15: lconst_1 16: lsub 17: lstore_2 18: goto 8 21: invokestatic #4; //Method java/lang/System.currentTimeMillis:()J 24: lload_0 25: lsub 26: lstore_2 27: getstatic #7; //Field java/lang/System.out:Ljava/io/PrintStream; 30: lload_2 31: invokevirtual #8; //Method java/io/PrintStream.println:(J)V 34: return public static void increment(); Code: 0: invokestatic #4; //Method java/lang/System.currentTimeMillis:()J 3: lstore_0 4: lconst_1 5: lstore_2 6: lload_2 7: ldc2_w #5; //long 100000000l 10: lcmp 11: ifge 21 14: lload_2 15: lconst_1 16: ladd 17: lstore_2 18: goto 6 21: invokestatic #4; //Method java/lang/System.currentTimeMillis:()J 24: lload_0 25: lsub 26: lstore_2 27: getstatic #7; //Field java/lang/System.out:Ljava/io/PrintStream; 30: lload_2 31: invokevirtual #8; //Method java/io/PrintStream.println:(J)V 34: return
這里為什么要把i置為100億,因為在這個數字下面他們之間的區別才明顯:27765ms,38516ms;經多次測試i++略耗時些。
其實還是不知道原來是什么....