SwiftUI List在MacOS中的性能优化示例

 

引言

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倍。 因为只加载了显示的部分,所以性能提升巨大。

以上就是SwiftUI List在MacOS中的性能优化示例的详细内容,更多关于SwiftUI List性能优化MacOS的资料请关注编程宝库其它相关文章!

 泛型(Generics)1、泛型可以将类型参数化,提高代码复用率,减少代码量func swapValue<T>(_ a: inout T, _ b: inout T) -> ...