1

I am trying to sort a very large array in my mobile app. I am using SwiftUI and would like the array to be sorted once the user taps on a button. This sorting can take about 3 seconds, so I would like this to happen off the main queue. However even when calling the code to happen on a global async block it still seems to happen on thread 1 and slow down my UI. During this time CPU spikes to 100% and the UI is unresponsive.

Button("Sort List") {
    DispatchQueue.global(qos: .background).async {
        self.updateList()
    }
}

...

func updateList() {
    //have tried putting the queue here as well
    var sorted: [OBJ] = []
    for obj in self.allObjs {
       for i in 0..<self.selected.count {
           ...
           let i = sorted.insertionIndexOf(obj, isOrderedBefore: self.sorter)
           sorted.insert(obj, at: i)
        }
     }
     self.someStateVar = sorted
}
Matt Bart
  • 809
  • 1
  • 7
  • 26

2 Answers2

0

Try the below explicit redirection to main queue.

Note: more provided code would allow to perform better analyses

func updateList() {
    //have tried putting the queue here as well
    var sorted: [OBJ] = []
    for obj in self.allObjs {
       for i in 0..<self.selected.count {
           ...
           let i = sorted.insertionIndexOf(obj, isOrderedBefore: self.sorter)
           sorted.insert(obj, at: i)
        }
     }
     DispatchQueue.main.async {
        self.someStateVar = sorted   // update on main queue
     }
}
Asperi
  • 228,894
  • 20
  • 464
  • 690
0

Are you sure this part of code does what you would like to do?

var sorted: [OBJ] = []

for obj in self.allObjs {
   for i in 0..<self.selected.count {
       ...
       let i = sorted.insertionIndexOf(obj, isOrderedBefore: self.sorter)
       sorted.insert(obj, at: i)
    }
 }

For me, it looks a little bit strange :-)

  1. What type is OBJ?
  2. Is selected part of some model or state? Is it related to UI?
  3. Is sorted an empty array?
  4. insertionIndexOf(obj, isOrderedBefore: self.sorter)? Where is this function from? Is it part of a custom sorting algorithm?
  5. Do you really would like to redefine i? If yes, where i (as a parameter in your loop) is used and for what?

I know this is not an answer but a lot of questions :-). If you need an answer, rewrite your question such a way, we can run and play within our environment.

user3441734
  • 16,722
  • 2
  • 40
  • 59