File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change @@ -2477,6 +2477,44 @@ Java标准库中使用的排序算法被设计为最适合您正在排序的类
24772477< ! -- Sorting in Parallel -- >
24782478## 并行排序
24792479
2480+ 如果排序性能是一个问题,那么可以使用 ** Java 8 parallelSort()** ,它为所有不可预见的情况(包括数组的排序区域或使用了比较器)提供了重载版本。为了查看相比于普通的sort(), ** parallelSort()** 的优点,我们使用了用来验证代码时的 ** JMH ** :
2481+
2482+ ```java
2483+ // arrays/jmh/ParallelSort.java
2484+ package arrays. jmh;
2485+
2486+ import onjava. * ;
2487+ import org. openjdk. jmh. annotations. * ;
2488+
2489+ import java.util. Arrays ;
2490+
2491+ @State (Scope . Thread )
2492+ public class ParallelSort {
2493+ private long [] la;
2494+
2495+ @Setup
2496+ public void setup () {
2497+ la = new Rand .Plong (). array(100_000 );
2498+ }
2499+
2500+ @Benchmark
2501+ public void sort () {
2502+ Arrays . sort(la);
2503+ }
2504+
2505+ @Benchmark
2506+ public void parallelSort () {
2507+ Arrays . parallelSort(la);
2508+ }
2509+ }
2510+ ```
2511+
2512+ ** parallelSort()** 算法将大数组拆分成更小的数组,直到数组大小达到极限,然后使用普通的 ** Arrays .sort()** 方法。然后合并结果。该算法需要不大于原始数组的额外工作空间。
2513+
2514+ 您可能会看到不同的结果,但是在我的机器上,并行排序将速度提高了大约3 倍。由于并行版本使用起来很简单,所以很容易考虑在任何地方使用它,而不是
2515+ ** Arrays . sort ()** 。当然,它可能不是那么简单—看看微基准测试。
2516+
2517+
24802518< ! -- Searching with Arrays . binarySearch() -- >
24812519## binarySearch二分查找
24822520
You can’t perform that action at this time.
0 commit comments