I came to SwiftUI from UIKit world and wondered how lists work in SwiftUI. This topic is a continuation of the topic about ForEach.
The question is how to make sure that the list of elements is effective in terms of memory management and speed.
So I came up with two different implementations:
- List of cells based on
List
:
List {
ForEach(0..<469) { i in
MyCellView(num: i)
.frame(height: 40)
}
}
- List of cells based on
VStack
:
ScrollView {
VStack {
ForEach(0..<469) { i in
MyCellView(num: i)
.frame(height: 40)
}
}
}
- List of cells based on
LazyVStack
:
ScrollView {
LazyVStack {
ForEach(0..<469) { i in
MyCellView(num: i)
.frame(height: 40)
}
}
}
Seems like ForEach
acts like a generator which supply the parent view with new items.
In the example 2 with VStack
, the memory graph shows a lot of pre-defined structures (as expected 469 in my case):
Does it means that they are pre-rendered or just structures in memory?
In opposite to 2, examples 1 and 3 are requesting only the number of cells which is displayed on the screen.
But still, the main questions is how to make sure that SwiftUI reuses the cells as UITableView
did and avoid memory overflow?