List of SwiftUI very lag when scroll with realtime data (item of array quick change)

I have a List and about 1000 item of Array, and my item update realtime (100 messenger updated/s). My List is very very lag. I see ForEach run full (1000 turn)/ (1 item update) => crazy Can you help me a solution like a reloadRows in UIKit with UITableView.

Thank so much!

This my test code (I try with List and LazyVStack):

struct PriceBoardView2 : View {
  @EnvironmentObject var loadingEnv : LoadingEnv
  @State var listUser : [UserModel]
   
  var body: some View {
    VStack(content: {
      Button(action: {
        updateData() //fake data realtime update
      }, label: {
        Text("Fake data realtime update")
      })
      List(content: {
        ForEach(listUser.indices, id: \.self) { i in
          RowPriceBoardView2(userModel: listUser[i])
        }
      })
//      ScrollView(content: {
//        LazyVStack(content: {
//          ForEach(listUser.indices, id: \.self) { i in
//            RowPriceBoardView2(userModel: listUser[i])
//          }
//        })
//      })
    })
    .onAppear(perform: {
      for i in 0..<1000 {
        listUser.append(UserModel(number: i, name: "-", age: 0))
      }
    })
  }
   
  func updateData() {
    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.01, execute: {
      let i = Int.random(in: 0..<1000)
      self.listUser[i] = UserModel(number: i, name: "Pla pla", age: Int.random(in: 0..<1000))
      updateData()
    })
  }
}


struct UserModel {
  var number : Int
   var name : String
   var age : Int
}

struct RowPriceBoardView2: View {
  var userModel : UserModel
   
  var body: some View {
    HStack(content: {
      Text("\(userModel.number)")
      Spacer()
      Text("\(userModel.name)")
      Spacer()
      Text("\(userModel.age)")
    })
    .frame(width: .infinity, height: 30, alignment: .center)
  }
}

On tapping "Fake data realtime update":

  • you start an infinite loop of updataData()
  • which calls itself (100 times a second)

For me, this pins CPU activity at 100%
Considering that, I found your code surprisingly responsive, I expected it to grind to a halt!

Updates may be arriving rapidly, but does your UI really need to update 100 times per second?
I think in a real app, a more realistic strategy would be to gather a batch of updates, and update the UI once, with the entire batch.

And of course, non-UI work need not be on the main thread.

List of SwiftUI very lag when scroll with realtime data (item of array quick change)
 
 
Q