日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

SwiftUI?List在MacOS中的性能優化示例_Swift

作者:liaoWorkin ? 更新時間: 2022-10-30 編程語言

引言

List在iOS中有懶加載的特性,但是在MacOS中會一次性加載完List中的所有的數據。并沒有懶加載的特性。

所以在MacOS的List中當數據量巨大時,會存在巨大的性能瓶頸。

  var body: some View {
    List(){
        ForEach(currentSectionModel) { (sectionModel) in
            Section(header:
                        HStack {
                Text("section")+Text(sectionModel.word).font(.title).foregroundColor(.red)
                        }.frame(height:35)
            ) {
              ForEach(currentSectionModel, id: \.self) { (wordModel) in
                  Text(wordModel.word)
                }
            }
        }
    }

當數據量達到15000條時, 在16寸i9的mbp上加載時長需要4.53s

這個時候建議使用 ScrollView + LazyVStack(macOS 11, iOS14支持)

ScrollView {
    LazyVStack {
    }
}

來獲取巨大性能提升

  var body: some View {
    ScrollView {
        LazyVStack {
            ForEach(currentSectionModel) { (sectionModel) in
                Section(header:
                            HStack {
                    Text("section")+Text(sectionModel.word).font(.title).foregroundColor(.red)
                            }.frame(height:35)
                ) {
                  ForEach(currentSectionModel, id: \.self) { (wordModel) in
                      Text(wordModel.word)
                    }
                }
            }
        }
    }.onAppear {
        DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
            currentSectionModel = storeData
        }
    }
}

實測加載15000 條數據加載時長為31ms 加載時長為原來的 0.0068倍。 因為只加載了顯示的部分,所以性能提升巨大。

原文鏈接:https://juejin.cn/post/7138687207426457630

欄目分類
最近更新