List在iOS中有懶加載的特性宣渗,但是在MacOS中會(huì)一次性加載完List中的所有的數(shù)據(jù)。并沒(méi)有懶加載的特性秸脱。
所以在MacOS的List中當(dāng)數(shù)據(jù)量巨大時(shí)落包,會(huì)存在巨大的性能瓶頸。
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)
}
}
}
}
當(dāng)數(shù)據(jù)量達(dá)到15000條時(shí)摊唇, 在16寸i9的mbp上加載時(shí)長(zhǎng)需要4.53s
這個(gè)時(shí)候建議使用 ScrollView + LazyVStack(macOS 11, iOS14支持)
ScrollView {
LazyVStack {
}
}
來(lái)獲取巨大性能提升
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
}
}
}
實(shí)測(cè)加載15000 條數(shù)據(jù)加載時(shí)長(zhǎng)為31ms 加載時(shí)長(zhǎng)為原來(lái)的 0.0068倍咐蝇。
因?yàn)橹患虞d了顯示的部分,所以性能提升巨大。