Java 7 sorting “optimisation”

前端 未结 3 1844
长发绾君心
长发绾君心 2021-02-03 23:54

In Java6 both quicksort and mergesort were used in Arrays#sort, for primitive and object arrays respectively. In Java7 these have both changed, to DualPivotQuickso

3条回答
  •  不要未来只要你来
    2021-02-04 00:28

    I wrote 2 methods test1 and test2 and add the main part of the compiled byte code (Java 1.6 on Snow Leopard) as comment:

        /*
         *     14  iload_1 [b]      -> load value from address 1 to sack
         *     15  iastore          -> store value from stack into int array
         *     16  iinc 3 1 [i]     -> int increment value of address 3
         *     19  iinc 3 1 [i]     -> int increment value of address 3
         */
        public void test1() {
            int b = 0;
            int a[] = new int[10];
            for (int i=0; i<10; i++) {
                a[i] = b; 
                i++;
            }
        }
    
        /*
         *     14  iinc 3 1 [i]     -> increment value of address 3
         *     17  iload_1 [b]      -> load value from address 1 to stack
         *     18  iastore          -> store value from stack into int array
         *     19  iinc 3 1 [i]     -> increment value of address 3 
         */
        public void test2() {
            int b = 0;
            int a[] = new int[10];
            for (int i=0; i<10; i++) {
                a[i++] = b;
            }
        }
    

    The order of the inc ops is different. But the operation sum of both methods test1 and test2 are equal! So the byte codes performance should be the same, too.

提交回复
热议问题