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

作者:liaoWorkin

%s 个评论

要回复文章请先登录注册