面试题: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 IncreamentCompiled from "Increament.java"public class Increament extends java.lang.Object{public Increament(); Code: 0: aload_0 1: invokespecial #1; //Method java/lang/Object."":()V 4: returnpublic static void main(java.lang.String[]) throws java.lang.InterruptedException; Code: 0: invokestatic #2; //Method decrement:()V 3: invokestatic #3; //Method increment:()V 6: returnpublic 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: returnpublic 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++略耗时些。
其实还是不知道原来是什么....