Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

206
Vistas
What are the benefits of using DispatchWorkItem in swift?

Suppose we have the following code defining a continuous loop (as in for a game):

let queue = DispatchQueue(label: "DemoSerialQueue")
let workItem = DispatchWorkItem{ print("Hello World") }
func gameLoop() {
  queue.async(execute:workItem)
}

Would the above code be more efficient in terms of speed than the following:

func gameLoop() {
  queue.async{ print("Hello World") }
}

In particular I'm wondering if the second form would be allocating a closure on every loop and thus incuring a performance hit.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

The DispatchWorkItem class is an encapsulation of the concept of work item. There are few benefits.

A dispatch work item has a cancel flag. If it is cancelled before running, the dispatch queue won’t execute it and will skip it. If it is cancelled during its execution, the cancel property return True. In that case, we can abort the execution

By encapsulating our request code in a work item, we can very easily cancel it whenever it's replaced by a new one, like this:

class SearchViewController: UIViewController, UISearchBarDelegate {
    // We keep track of the pending work item as a property
    private var pendingRequestWorkItem: DispatchWorkItem?

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        // Cancel the currently pending item
        pendingRequestWorkItem?.cancel()

        // Wrap our request in a work item
        let requestWorkItem = DispatchWorkItem { [weak self] in
            self?.resultsLoader.loadResults(forQuery: searchText)
        }

        // Save the new work item and execute it after 250 ms
        pendingRequestWorkItem = requestWorkItem
        DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(250),
                                      execute: requestWorkItem)
    }
}

In general, Dispatch functions can take a block or a DispatchWorkItem as a parameter. So there won't any performance hit as we use blocks in both cases. Use the one that suits you the most.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda