AVt天堂网 手机版,亚洲va久久久噜噜噜久久4399,天天综合亚洲色在线精品,亚洲一级Av无码毛片久久精品

當前位置:首頁 > 科技  > 軟件

為什么list.sort()比Stream().sorted()更快?

來源: 責編: 時間:2023-09-18 21:41:46 335觀看
導讀看到一個評論,里面提到了list.sort()和list.strem().sorted()排序的差異。說到list.sort()排序比stream().sorted()排序性能更好。但沒說到為什么。有朋友也提到了這一點。本文重新開始,先問是不是,再問為什么。真的更好

看到一個評論,里面提到了list.sort()和list.strem().sorted()排序的差異。MNV28資訊網——每日最新資訊28at.com

說到list.sort()排序比stream().sorted()排序性能更好。MNV28資訊網——每日最新資訊28at.com

但沒說到為什么。MNV28資訊網——每日最新資訊28at.com

MNV28資訊網——每日最新資訊28at.com

有朋友也提到了這一點。MNV28資訊網——每日最新資訊28at.com

本文重新開始,先問是不是,再問為什么。MNV28資訊網——每日最新資訊28at.com

真的更好嗎?

先簡單寫個 demo。MNV28資訊網——每日最新資訊28at.com

List<Integer> userList = new ArrayList<>();    Random rand = new Random();    for (int i = 0; i < 10000 ; i++) {        userList.add(rand.nextInt(1000));    }    List<Integer> userList2 = new ArrayList<>();    userList2.addAll(userList);    Long startTime1 = System.currentTimeMillis();    userList2.stream().sorted(Comparator.comparing(Integer::intValue)).collect(Collectors.toList());    System.out.println("stream.sort耗時:"+(System.currentTimeMillis() - startTime1)+"ms");    Long startTime = System.currentTimeMillis();    userList.sort(Comparator.comparing(Integer::intValue));    System.out.println("List.sort()耗時:"+(System.currentTimeMillis()-startTime)+"ms");

輸出:MNV28資訊網——每日最新資訊28at.com

stream.sort耗時:62msList.sort()耗時:7ms

由此可見 list 原生排序性能更好。MNV28資訊網——每日最新資訊28at.com

能證明嗎?MNV28資訊網——每日最新資訊28at.com

不一定吧。MNV28資訊網——每日最新資訊28at.com

再把 demo 變換一下,先輸出stream.sort。MNV28資訊網——每日最新資訊28at.com

List<Integer> userList = new ArrayList<>();Random rand = new Random();for (int i = 0; i < 10000 ; i++) {    userList.add(rand.nextInt(1000));}List<Integer> userList2 = new ArrayList<>();userList2.addAll(userList);Long startTime = System.currentTimeMillis();userList.sort(Comparator.comparing(Integer::intValue));System.out.println("List.sort()耗時:"+(System.currentTimeMillis()-startTime)+"ms");Long startTime1 = System.currentTimeMillis();userList2.stream().sorted(Comparator.comparing(Integer::intValue)).collect(Collectors.toList());System.out.println("stream.sort耗時:"+(System.currentTimeMillis() - startTime1)+"ms");

此時輸出變成了:MNV28資訊網——每日最新資訊28at.com

List.sort()耗時:68msstream.sort耗時:13ms

這能證明上面的結論錯誤了嗎?MNV28資訊網——每日最新資訊28at.com

都不能。MNV28資訊網——每日最新資訊28at.com

兩種方式都不能證明到底誰更快。MNV28資訊網——每日最新資訊28at.com

使用這種方式在很多場景下是不夠的,某些場景下,JVM 會對代碼進行 JIT 編譯和內聯優化。MNV28資訊網——每日最新資訊28at.com

Long startTime = System.currentTimeMillis();...System.currentTimeMillis() - startTime

此時,代碼優化前后執行的結果就會非常大。MNV28資訊網——每日最新資訊28at.com

基準測試是指通過設計科學的測試方法、測試工具和測試系統,實現對一類測試對象的某項性能指標進行定量的和可對比的測試。MNV28資訊網——每日最新資訊28at.com

基準測試使得被測試代碼獲得足夠預熱,讓被測試代碼得到充分的 JIT 編譯和優化。MNV28資訊網——每日最新資訊28at.com

下面是通過 JMH 做一下基準測試,分別測試集合大小在 100,10000,100000 時兩種排序方式的性能差異。MNV28資訊網——每日最新資訊28at.com

import org.openjdk.jmh.annotations.*;import org.openjdk.jmh.infra.Blackhole;import org.openjdk.jmh.results.format.ResultFormatType;import org.openjdk.jmh.runner.Runner;import org.openjdk.jmh.runner.RunnerException;import org.openjdk.jmh.runner.options.Options;import org.openjdk.jmh.runner.options.OptionsBuilder;import java.util.*;import java.util.concurrent.ThreadLocalRandom;import java.util.concurrent.TimeUnit;import java.util.stream.Collectors;@BenchmarkMode(Mode.AverageTime)@OutputTimeUnit(TimeUnit.MICROSECONDS)@Warmup(iterations = 2, time = 1)@Measurement(iterations = 5, time = 5)@Fork(1)@State(Scope.Thread)public class SortBenchmark {    @Param(value = {"100", "10000", "100000"})    private int operationSize;     private static List<Integer> arrayList;    public static void main(String[] args) throws RunnerException {        // 啟動基準測試        Options opt = new OptionsBuilder()            .include(SortBenchmark.class.getSimpleName())             .result("SortBenchmark.json")            .mode(Mode.All)            .resultFormat(ResultFormatType.JSON)            .build();        new Runner(opt).run();     }    @Setup    public void init() {        arrayList = new ArrayList<>();        Random random = new Random();        for (int i = 0; i < operationSize; i++) {            arrayList.add(random.nextInt(10000));        }    }    @Benchmark    public void sort(Blackhole blackhole) {        arrayList.sort(Comparator.comparing(e -> e));        blackhole.consume(arrayList);    }    @Benchmark    public void streamSorted(Blackhole blackhole) {        arrayList = arrayList.stream().sorted(Comparator.comparing(e -> e)).collect(Collectors.toList());        blackhole.consume(arrayList);    }}

性能測試結果:MNV28資訊網——每日最新資訊28at.com

MNV28資訊網——每日最新資訊28at.com

可以看到,list.sort()效率確實比stream().sorted()要好。MNV28資訊網——每日最新資訊28at.com

為什么更好?MNV28資訊網——每日最新資訊28at.com

流本身的損耗

java 的 stream 讓我們可以在應用層就可以高效地實現類似數據庫 SQL 的聚合操作了,它可以讓代碼更加簡潔優雅。MNV28資訊網——每日最新資訊28at.com

但是,假設我們要對一個 list 排序,得先把 list 轉成 stream 流,排序完成后需要將數據收集起來重新形成 list,這部份額外的開銷有多大呢?MNV28資訊網——每日最新資訊28at.com

我們可以通過以下代碼來進行基準測試:MNV28資訊網——每日最新資訊28at.com

import org.openjdk.jmh.annotations.*;import org.openjdk.jmh.infra.Blackhole;import org.openjdk.jmh.results.format.ResultFormatType;import org.openjdk.jmh.runner.Runner;import org.openjdk.jmh.runner.RunnerException;import org.openjdk.jmh.runner.options.Options;import org.openjdk.jmh.runner.options.OptionsBuilder;import java.util.ArrayList;import java.util.Comparator;import java.util.List;import java.util.Random;import java.util.concurrent.TimeUnit;import java.util.stream.Collectors;@BenchmarkMode(Mode.AverageTime)@OutputTimeUnit(TimeUnit.MICROSECONDS)@Warmup(iterations = 2, time = 1)@Measurement(iterations = 5, time = 5)@Fork(1)@State(Scope.Thread)public class SortBenchmark3 {    @Param(value = {"100", "10000"})    private int operationSize; // 操作次數    private static List<Integer> arrayList;    public static void main(String[] args) throws RunnerException {        // 啟動基準測試        Options opt = new OptionsBuilder()            .include(SortBenchmark3.class.getSimpleName()) // 要導入的測試類            .result("SortBenchmark3.json")            .mode(Mode.All)            .resultFormat(ResultFormatType.JSON)            .build();        new Runner(opt).run(); // 執行測試    }    @Setup    public void init() {        // 啟動執行事件        arrayList = new ArrayList<>();        Random random = new Random();        for (int i = 0; i < operationSize; i++) {            arrayList.add(random.nextInt(10000));        }    }    @Benchmark    public void stream(Blackhole blackhole) {        arrayList.stream().collect(Collectors.toList());        blackhole.consume(arrayList);    }    @Benchmark    public void sort(Blackhole blackhole) {        arrayList.stream().sorted(Comparator.comparing(Integer::intValue)).collect(Collectors.toList());        blackhole.consume(arrayList);    }}

方法 stream 測試將一個集合轉為流再收集回來的耗時。MNV28資訊網——每日最新資訊28at.com

方法 sort 測試將一個集合轉為流再排序再收集回來的全過程耗時。MNV28資訊網——每日最新資訊28at.com

測試結果如下:MNV28資訊網——每日最新資訊28at.com

MNV28資訊網——每日最新資訊28at.com

可以發現,集合轉為流再收集回來的過程,肯定會耗時,但是它占全過程的比率并不算高。MNV28資訊網——每日最新資訊28at.com

因此,這部只能說是小部份的原因。MNV28資訊網——每日最新資訊28at.com

排序過程

我們可以通過以下源碼很直觀的看到。MNV28資訊網——每日最新資訊28at.com

MNV28資訊網——每日最新資訊28at.com

  • 1 begin方法初始化一個數組。
  • 2 accept 接收上游數據。
  • 3 end 方法開始進行排序。

這里第 3 步直接調用了原生的排序方法,完成排序后,第 4 步,遍歷向下游發送數據。MNV28資訊網——每日最新資訊28at.com

所以通過源碼,我們也能很明顯地看到,stream()排序所需時間肯定是 > 原生排序時間。MNV28資訊網——每日最新資訊28at.com

只不過,這里要量化地搞明白,到底多出了多少,這里得去編譯 jdk 源碼,在第 3 步前后將時間打印出來。MNV28資訊網——每日最新資訊28at.com

這一步我就不做了。MNV28資訊網——每日最新資訊28at.com

感興趣的朋友可以去測一下。MNV28資訊網——每日最新資訊28at.com

不過我覺得這兩點也能很好地回答,為什么list.sort()比Stream().sorted()更快。MNV28資訊網——每日最新資訊28at.com

補充說明:MNV28資訊網——每日最新資訊28at.com

  • 本文說的 stream() 流指的是串行流,而不是并行流。
  • 絕大多數場景下,幾百幾千幾萬的數據,開心就好,怎么方便怎么用,沒有必要去計較這點性能差異。

本文鏈接:http://www.tebozhan.com/showinfo-26-10468-0.html為什么list.sort()比Stream().sorted()更快?

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: C++中表達式的必要性

下一篇: 分布式事務原理及解決方案

標簽:
  • 熱門焦點
Top