printDavid
printDavid

Reputation: 235

why is the swiftUI list not lazy (compared to lazyVStack)?

are lists in SwiftUI really lazy? I am having a list of 5000 elements fetched from coreData and I want to display them in a list. I read a lot of comments (like that: https://developer.apple.com/forums/thread/651256) that Lists are lazy but for me it looks like they are not.... Loading the list takes 15 seconds.

List(element,  id: \.objectID, selection: $selection) { file in 
    RowView(file)
}
     

If I use a ScrollView + LazyVStack + ForEach instead the loading takes less than a second.

ScrollView {
    LazyVStack(alignment: .leading, spacing: 0) {
         ForEach(element, id: \.objectID) { file in
             RowView(file)
                .onTapGesture {
                    selection = Set([file.objectID])
                }
         }
    }
}
            

I would prefer taking a list to make use of the functionalities it provides. Am I doing something wrong or is list not lazy?

Thanks for help! (i am working with SwiftUI (for Mac)).

Upvotes: 12

Views: 4987

Answers (1)

gswierczynski
gswierczynski

Reputation: 4173

I read everywhere that List is supposed to be Lazy on iOS but following snippet seems to contradict it

import SwiftUI

struct Item {
    var id: Int
}

let items = (1...30000)
    .map { v in
        Item(id: v)
    }

struct ItemRow:View{
    let item: Item
    init(item: Item){
        self.item = item
        print("init #\(item.id)")
    }
    var body: some View{
        Text(String(item.id))
    }
}

struct ContentView: View {
    var body: some View {
//        ScrollView {
//            LazyVStack {
//                ForEach(items, id: \.id) { item in
//                    ItemRow(item: item)
//                }
//            }
//        }
        List(items, id: \.id) { item in
            ItemRow(item: item)
        }
    }
}

This prints out 30000 times twice (new empty project). Also checked that ItemRow's body is also called for all 30k items immediately.

Am I missing something?

Upvotes: 1

Related Questions