How expensive is it to call executeFetchRequest on the managedObjectContext? Does it depend on the data set size? Is this something that can be done often or should be avoided as much as possible?
Fetch requests allow us to load Core Data results that match specific criteria we specify, and SwiftUI can bind those results directly to user interface elements. If you followed my Core Data and SwiftUI set up instructions, you've already injected your managed object context into the SwiftUI environment.
A description of search criteria used to retrieve data from a persistent store.
Fetching Data From CoreData We have created a function fetch() whose return type is array of College(Entity). For fetching the data we just write context. fetch and pass fetchRequest that will generate an exception so we handle it by writing try catch, so we fetched our all the data from CoreData.
The predicate instance constrains the selection of objects the NSFetchRequest instance is to fetch. If the predicate is empty—for example, if it is an AND predicate whose array of elements contains no predicates—the request has its predicate set to nil .
As with most things, pre-optimization is never a good thing. Fetching itself is rarely the bottleneck for an application and when it is it will be apparent very quickly.
I generally do not concern myself with the performance of fetches, or even faulting, until I notice a performance issue. Then it is time for optimizations.
Until you have the application put together and are running data through it on actual hardware, it is quite difficult, and generally a wast of time, to guess where the bottlenecks are going to be. Build, test and observe.
It's relatively expensive. Each fetch you execute implies a round trip from the context through the model to the persistent store, which itself implies a file access. At best, your fetch will be as slow as the access to the store's file. In certain cases (especially fetching large binary BLOBs), it will be considerably slower. Fetch with caution.
However, remember that a fetch is not as expensive as firing a fault. You should worry more about firing faults to access data than you should doing additional fetches. Additionally, executing one or a few large fetches is considerably less expensive than running many small fetches (much like accessing one large file is easier than accessing a hundred small ones).
The best policy is to try to anticipate when designing your app what data will be necessary, then fetch it at once or in a few large fetches and cache it as long as you can.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With