LazyVStack is not always lazy. why ??


struct ContentView: View {
    var body: some View {
        ScrollView(.vertical) {
            LazyVStack(spacing: 0) {
                ForEach(0..<10000) { index in
                    
                    // If VStack remove, memory issue occur
//                    VStack {
                        CustomView(index: index)
//                    }
                }
            }
        }
    }
}

struct CustomView: View {
    
    var index: Int
    
    var body: some View {
        VStack {
            Text("\(index)")
        }
    }
}

I wrapped it into a shorter and simpler version, but it still works.

At first, I struggled to figure out why the initial code was causing lag. After investigating with the Debug Memory Graph, I found that the generated custom view’s memory was not being released properly.

This seemed strange because I was using the custom view inside a LazyHStack.

So, I tried various approaches to resolve the issue.

In the Debug Memory Graph, I started suspecting that SwiftUI’s built-in views like VStack and HStack might be affecting memory management. To test this, I wrapped my custom view inside a VStack, and the memory issue disappeared.

However, I want to understand why I need to include the custom view inside a VStack for proper memory management.

(I simplified this code by wrapping it into a shorter version. However, in a real project, the custom view is more complex, and the data list contains more than 10,000 items. This caused severe lag.)

xcode: 16.2, iOS 18, iOS 16

Our engineering teams need to investigate this issue. I'd greatly appreciate it if you could open a bug report, include Code snippet and .trace file when you profile your app using the SwiftUI instrument template. Post the FB number here once you do.

Bug Reporting: How and Why? has tips on creating your bug report.

LazyVStack is not always lazy. why ??
 
 
Q