简体   繁体   中英

Java - Why does DualPivotQuicksort have duplicated code?

Looking at the jdk implementatino of Dual pivot quick sort there is plenty of duplicate code for every type of array. For example:

ints:

 static void sort(int[] a, int left, int right,
                 int[] work, int workBase, int workLen) {
    // Use Quicksort on small arrays
    if (right - left < QUICKSORT_THRESHOLD) {
        sort(a, left, right, true);
        return;
    }

longs:

 static void sort(long[] a, int left, int right,
                 long[] work, int workBase, int workLen) {
    // Use Quicksort on small arrays
    if (right - left < QUICKSORT_THRESHOLD) {
        sort(a, left, right, true);
        return;
    }

Why not just use T[] a and benefiting from autoboxing?

This is done for performance reasons. Generic T[] cannot be used in place of an array of primitive int s or long s, so without an overload with int[] or long[] the users would be forced to use the generic that uses boxed Long s and Integer s.

You would not be able to benefit from autoboxing here, either, because autoboxing is defined for individual primitives, not for arrays of primitives.

private static <T> void doSomething(T[] array){
    ...
}
public static void main (String[] args) throws java.lang.Exception {
    doSomething(new String[10]); // Compiles fine
    doSomething(new int[10]);    // Compile-time error
}

Main.java:...: error: method doSomething in class ... cannot be applied to given types;

  doSomething(new int[10]); ^ required: T[] found: int[] 

reason: inference variable T has incompatible bounds equality constraints: int upper bounds: Object where T is a type-variable: T extends Object declared in method doSomething(T[])

Even if you could, the processing would be a lot slower, and it would require a lot of additional memory, because wrapping large arrays of primitives could be expensive.

Because that would open it to all possible objects, in which case you would need to implement a compareTo method to be able to sort objects in some way.

The compiler keeps it simple. Numbers are nice.

Performance as well, working with objects requires much more memory that working with primitive types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM