1

Let's consider a list of 100 posts. According to Apple, if I layout them inside a LazyVStack:

the stack view doesn’t create items until it needs to render them onscreen.

What if I embed that LazyVStack inside a VStack? Does it still load the views "as needed"?

Sotiris Kaniras
  • 520
  • 1
  • 12
  • 30

1 Answers1

1
struct MyView: View {
    init() {
        print("init...")
    }
    
    var body: some View {
        Text("test")
    }
}

struct ContentView: View {
    var body: some View {
        ScrollView {
            VStack {
                LazyVStack {
                    ForEach.init(0..<100) { int in
                        MyView()
                    }
                }
            }
        }
    }
}

Running the above code, as we scroll we can see more MyViews are init'd (by viewing the print statements in the console), so it seems like a LazyVStack in a VStack does indeed create it's content lazily. We can see the same is true when removing the VStack as well.

  • Do they get released when they go off-screen as well? – Sotiris Kaniras Nov 18 '22 at 11:37
  • 1
    Using that same example, when we scroll to reveal all of the possible views, we can see that there are no more inits ever called. This leads me to believe that maybe not? But what's interesting is to think that it's not actually these structs that are displayed, but rather a view representing them. Maybe those views are deallocated even though the struct representing them is not. What matters here really is performance, right? So if, in your app, you don't notice any stuttering or memory pressure, you're good. This stuff should be an implementation detail we don't have to worry about! – Andrew Carter Nov 18 '22 at 17:28
  • That actually makes a lot of sense! Although `struct` initialization is fast, it can’t be deallocated entirely every time its view is off-screen. On the other hand, in a `UITableView` it's the opposite behavior; the cells are recycled, but obviously, the models don't. – Sotiris Kaniras Nov 18 '22 at 17:44