Search code examples
swiftswift-concurrency

Synchronous function inside Task or outside - any difference?


Will there be any difference in running a function that is not marked as async and running it inside a Task?

.onChange(of: callState.current) { state in
    viewModel.changeNavigation(title: state.controllerTitle) // 1 - outside
    Task {
        viewModel.changeNavigation(title: state.controllerTitle) // 2 - inside
        Task.detached(priority: .background) {
            await viewModel.audit(state: state)
        }
    }
}

onChange is called from MainActor (SwiftUI View). Both options are executed on the main thread. Is there any difference in the performance exerted on the main thread and UI?


Solution

  • The difference is how the function runs relative to code around it. With the viewModel.changeNavigation code outside of the task, it will certainly run before any of the code that follows it.

    With it inside the task you know that it will run at some point in the future, but you don't have any idea what other code might run before it.

    If something else has been sent to the main queue it might execute first. If there are other tasks in the same execution context they could run before that call too.

    The performance impact of creating the task and having it work through the scheduler is non-zero, but at user interface speeds probably won't be noticeable.

    But you've definitely changed the timing of when the code will run and that may cause race conditions and the like if you're not careful.