SoFunction
Updated on 2025-04-06

Example of SwiftUI List's performance optimization in MacOS

introduction

List has the feature of lazy loading in iOS, but in MacOS, all data in List will be loaded at once. There is no lazy loading feature.

Therefore, when the data volume in MacOS List is huge, there will be huge performance bottlenecks.

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

When the data volume reaches 15,000 pieces, the loading time on the mbp of 16-inch i9 takes 4.53s

At this time, it is recommended to use ScrollView + LazyVStack (macOS 11, iOS14 supports)

ScrollView {
    LazyVStack {
    }
}

To get huge performance improvements

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

The actual loading time of 15,000 pieces of data is 31ms and the loading time is 0.0068 times the original. Because only the displayed part is loaded, the performance improvement is huge.

The above is the detailed content of the performance optimization example of SwiftUI List in MacOS. For more information about SwiftUI List performance optimization MacOS, please follow my other related articles!