

If you load them in a background context, and present the loaded objects in the views, your app will crash since CoreData expects to be run on a single thread. If you are using the ViewContext in CoreData, which means you will load them on the main thread, you might notice some performance implications. Not only this data needs to be loaded from the database, but it also needs to be grouped daily, monthly or in any other way, and this requires further computations. This data can be available weekly, monthly, yearly etc. Imagine that you are building an app that displays stats data in a graph or something similar.

The same underlying issue can appear in many other different scenarios, like database access on the main queue.
#VSTACK VS LAZYVSTACK UPDATE#
This will update the view accordingly, and it will avoid unecessary additional loads of the attachment. a ViewModel), do the loading work in a background queue, and update the dictionary on the main queue when we’re done. If we want to validate that it’s also a valid attachment before showing the icon, we can add a dictionary with all the attachments in our view display logic (e.g. We can just check if the attachmentURL is nil. In this case, we don’t need to load the whole attachment to check if it has an attachment. It returns just a boolean, but under the hood, it uses the whole attachment loading logic, which when applied on many rows has a significant performance impact. We use the second one in our view to determine if we should show the attachment icon.Ĭan you spot the bottleneck here? The problem is that the hasAttachment method will be called many times by SwiftUI. There are two computed variables here, one that loads the attachment and another one that checks if there’s an attachment. Let attachment = try JSONDecoder().decode(lf, from: attachmentData) Let attachmentData = try Data(contentsOf: attachmentURL) Let’s say we have a list that presents some data, and an optional attachment icon (indicating that there’s an attachment that can be opened on tap). SwiftUI frequently redraws its views, so having a slow operation referenced somewhere in the view definition will definitely have an impact on performance.


It’s interesting that these mistakes are subtle and sometimes hard to spot, especially if the method we are using is synchronous (without a callback, future or an async function). This is one of the most common sources of app sloweness. Heavy work on the main threadĪs a rule of thumb, no matter whether we are using SwiftUI or UIKit, we should avoid doing heavy work on the main thread. In order to improve our app’s performance, we need to reduce these animation hitches to a minimum (or even better, get rid of them altogether).
