Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 376
gloo Avatar asked Jan 06 '19 04:01

gloo


People also ask

What is DispatchWorkItem in Swift?

A DispatchWorkItem encapsulates work to be performed on a dispatch queue or a dispatch group. It is primarily used in scenarios where we require the capability of delaying or canceling a block of code from executing.

What is a DispatchWorkItem in GCD Grand Central Dispatch )? Swift?

What is DispatchWorkItem? DispatchWorkItem is used to store a task on a dispatch queue for later use, and you can perform operations several operations on it, you can even cancel the task if it is not required later in the code.

What is Dispatchqueue in Swift?

Dispatch queues are FIFO queues to which your application can submit tasks in the form of block objects. Dispatch queues execute tasks either serially or concurrently. Work submitted to dispatch queues executes on a pool of threads managed by the system.

What is a dispatchworkitem in iOS?

DispatchWorkItem encapsulates work that can be performed. A work item can be dispatched onto a DispatchQueue and within a DispatchGroup. A DispatchWorkItem can also be set as a DispatchSource event, registration, or cancel handler. — Apple’s Documentation

How to submit work item to dispatchqueue or dispatchgroup?

We can submit the work item for execution to DispatchQueue or DispatchGroup, by doing this, it only specifies the executing queue or group. We can also call perform(), but it executes the work item on the calling thread only.

What is the use of dispatchworkitem Flags?

DispatchWorkItemFlags is basically a set of unique options that can customize the behaviour of DispatchWorkItem. Depending on the flag value you provided, it decides whether to create a new thread or need to create a barrier.✅

What are the benefits of SwiftUI for mobile app development?

Safe and secured: The syntax of Swift native app development would allow you to create a consistent and clean code. Not only this, SwiftUI also offers safeguards to rectify all the errors as well as improve readability. Faster approach: We can see that the community built Swift development with bringing out greater performance in their mind.


1 Answers

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.

like image 177
Dinesh Selvaraj Avatar answered Oct 11 '22 23:10

Dinesh Selvaraj