/ swift

A simple optimization for UICollectionView (or UITableView) updates

The problem:

Collection view is highly optimized and works great out of the box. It is really hard to slow it down or to make scrolling sloppy when the number of items displayed is relatively small (~ a couple of hundreds). Even doing reloadData every other second will not make a huge difference.
Troubles begin once the number of items starts growing.

Solution:

One simple way to improve CPU usage is to perform batch updates instead of reloading the entire data source each time new items are added to the data source.

func appendCollectionView(numberOfItems count:Int){
    
    if let viewModel = viewModel {
        // calculate indexes for the items to be added
        let firstIndex = dataSource.count - count
        let lastIndex = dataSource.count - 1
        
        var indexPaths = [IndexPath]()
        for index in firstIndex...lastIndex {
            let indexPath = IndexPath(item: index, section: 0)
            indexPaths.append(indexPath)
        }
        
        // finally update the collection view
        collectionView.performBatchUpdates({ () -> Void in
            collectionView.insertItems(at: indexPaths)
        }, completion: { (finished) -> Void in
            
        })
    }
}

In our case, CPU usage went down from 90% to 10%!