'Alternative to views in a VStack embedded in a List to improve performance

Code

Section {
    VStack {
        ForEach(Task.sampleData) { task in
            TaskRow(task: task)
        }
    }
    .overlay(
        RoundedRectangle(cornerRadius: 10)
            .stroke(Color("gray"), lineWidth: 1)
    )
} header: {
    HStack {
        Text("Today's Tasks")
            .textCase(.none)
            .font(.subheadline.bold())
            .foregroundColor(.black)
        Spacer()
        Button {
                        
        } label: {
            Text("Filter tasks")
            Image(systemName: "line.3.horizontal.decrease.circle")
        }
        .textCase(.none)
        .font(.subheadline)
        .foregroundStyle(Color("gray"))
    }
}

The Problem

The code above is a segment from the List view that produces the following result. This is exactly what I want the list to look like however because the Task rows are embedded in the VStack the list will reuse the VStack view which means the list will be unable to manage the amount of memory when initialising many Task row views some of which could be off screen. I see this as a problem for example if this VStack contained 1000 Task row views they would all be initialised into memory when the list is drawn on screen.

Background

The whole purpose of the VStack is not to layout the rows vertically but to provide a container so that a rounded border can be applied to however many rows that need to be drawn.

Solutions I have looked at

  1. I have looked at replacing the VStack with a LazyVStack but this solution seems more of a bandaid because once the user scrolls down to the bottom of the LazyVStack all of the rows will be initialised meaning we are back to square one and this is just a VStack again.
  2. I have looked at just applying the overlay to the Section however the overlay is applied to each element inside the section individually.
  3. To remove the VStack and instead draw the border inside the Task row. The row will need to know if it is at the top, bottom, or middle of the list so that it knows whether or not it will have rounded corners. This seems to be the only solution I can think of but it seems like a lot of work just to have a rounded rectangle drawn around a list section.


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source