Діма Комар Діма Комар - 3 months ago 10
iOS Question

How to speed up performance of a loop in Swift?

I'm just wondering if there is any way to boost speed of my loop, or suggestions for best practice, cause I feel it looks so bad.

Here is the code:

for (index, _) in filteredArray.enumerate() {
if index == 0 || index % 4 == 0 {
let mediaItem = Item()
mediaItem.id = filteredArray[index + 3]
let photoURL = NSURL(string: filteredArray[index + 1])
guard let url = photoURL else { return }
let data = NSData(contentsOfURL: url)
let finishImage = UIImage(data: data!)
mediaItem.Photo = finishImage
mediaItem.orderCount = filteredArray[index + 2]
mediaItem.UUId = filteredArray[index]
self.dataSourceItems.insert(mediaItem)
}
}

Answer

Try to use dispatch_apply. Something like that:

let iterationsCount = filteredArray.count / 4
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

dispatch_apply(iterationsCount, queue) { i in
    let index = i * 4
    let mediaItem = Item()
    mediaItem.id = filteredArray[index + 3]
    let photoURL = NSURL(string: filteredArray[index + 1])
    guard let url = photoURL else {  return  }
    let data = NSData(contentsOfURL: url)
    let finishImage = UIImage(data: data!)
    mediaItem.Photo = finishImage
    mediaItem.orderCount = filteredArray[index + 2]
    mediaItem.UUId = filteredArray[index]
    self.dataSourceItems.insert(mediaItem)
}

Notice that, depending on your situation, you may need to 1. use self inside closure, if you accessing properties; 2. add some locks if you write to shared memory.