Skip to content

Instantly share code, notes, and snippets.

@xmollv
Last active July 23, 2022 10:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xmollv/7ecc97d8118c100e85698c5ff09a20dc to your computer and use it in GitHub Desktop.
Save xmollv/7ecc97d8118c100e85698c5ff09a20dc to your computer and use it in GitHub Desktop.
import SwiftUI
@main
struct SwiftUIListVSLazyVStackApp: App {
let numbers = (0...100).map { $0 }
var body: some Scene {
WindowGroup {
/*
List calls the init & the body of *every* element on the list, even if it's not being displayed making it extremely slow.
*/
List(numbers) { number in
RowView(for: number, example: "list")
}
/*
A combination of ScrollView + LazyVStack achieves what's expected from the list. Only calls the init & body of
the element that's going to be displayed.
*/
// ScrollView {
// LazyVStack(alignment: .leading, spacing: 8) {
// ForEach(numbers) { number in
// RowView(for: number, example: "stack")
// }
// }
// }
}
}
}
struct RowView: View {
private let number: Int
private let example: String
init(for number: Int, example: String) {
print("Init \(example): \(number)")
self.number = number
self.example = example
}
var body: some View {
let _ = print("Body \(example): \(number)")
Text("\(number)")
.onAppear{ print("Appear \(example): \(number)") }
}
}
extension Int: Identifiable {
public var id: Int { self }
}
@xmollv
Copy link
Author

xmollv commented Apr 22, 2022

I realized about this due to performance issues. Look how different the behavior is when the list has 100_000 rows.

  1. List took ~12 seconds to render
  2. ScrollView + LazyVStack rendered instantly
Example.100K.mov

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment