В чём подвох, почему параллельная сортировка медленнее обычной?
public class Main {
public static void main(String[] args) throws Exception {
new Main().f();
}
void f() throws Exception {
int sz = (int) Math.pow(10, 7);
int[] a = new Random().ints(sz, 0, 10000).toArray();
int[] a1 = a.clone();
int[] a2 = a.clone();
long time1 = calcTime(() -> streamSort(a1));
long time2 = calcTime(() -> parallelStreamSort(a2));
System.out.println(time1);
System.out.println(time2);
}
List<Integer> streamSort(int[] a) {
return Arrays.stream(a).sorted().boxed().collect(Collectors.toList());
}
List<Integer> parallelStreamSort(int[] a) {
return Arrays.stream(a).parallel().sorted().boxed().collect(Collectors.toList());
}
long calcTime(Worker worker) throws Exception {
Instant start = Instant.now();
worker.doWork();
return Duration.between(start, Instant.now()).toMillis();
}
public interface Worker {
void doWork() throws Exception;
}
}
parallelSort()
, а в коде обычная.parallel().sorted()
. Как вариант тоже подходит.