SlideShare a Scribd company logo
1 of 18
Core Data Optimization
By Gagan Vishal Mishra
Memory Vs. Performance
Core Data Optimization
2
Memory
Speed
Less More
Slow Faster
Memory Vs. Performance
Core Data Optimization
3
Memory
Speed
Less More
Slow Faster
Thread Safety In Core Data
Core Data Optimization
4
• While working with Core Data, it's important to always remember that Core Data isn't
thread safe. Core Data expects to be run on a single thread.
• NSManagedObject, NSManagedObjectContext NSPersistentStoreCoordinator aren't
thread safe.
• This doesn't mean that every Core Data operation needs to be performed on the
main thread, which is used for UI, but it means that we need to take care which
operations are executed on which threads. We have to be careful how changes from
one thread are propagated to other threads.
Thread Safety In Core Data
Core Data Optimization
5
1. NSManagedObject: NSManagedObject isn't thread safe but has an
instance objectID that returns an instance of the NSManagedObjectID class which
is thread safe. For getting
do {
let managedObject = try managedObjectContext.existingObjectWithID(objectID)
} catch let fetchError as NSError { print("(fetchError), (fetchError.userInfo)”) }
2. NSManagedObjectContext: Isn't thread safe, we can create a managed object
context for every thread that interacts with Core Data. This strategy is referred
as thread confinement. A common approach is to create thread dictionary to store
MOC.
let currentThread = NSThread.currentThread()
currentThread.threadDictionary.setObject(managedObjectContext, forKey:
"managedObjectContext")
3. NSPersistentStoreCoordinator: We can create a separate persistent store
coordinator for every thread. Which is also possible.
Multithreading & Concurrency Strategies
Core Data Optimization
6
The NSPersistentStoreCoordinator class was designed to support multiple managed
object contexts, even if those managed object contexts were created on different
threads. Because the NSManagedObjectContext class locks the persistent store
coordinator while accessing it, it is possible for multiple managed object contexts to use
the same persistent store coordinator even if those managed object contexts live on
different threads. This makes a multithreaded Core Data setup much more manageable
and less complex.
There are two ways for Core Data Concurrency
1.Notifications
2.Parent/Child Managed Object Contexts
Another option is
1.Independent Persistent Store Built with Notification & PrivateQueue
Multithreading & Concurrency Strategies
Core Data Optimization
7
There are three types of Concurrency options provided by Apple
1.MainQueueConcurrencyType: The managed object context is only accessible from
the main thread. An exception is thrown if you try to access it from any other thread.
1.PrivateQueueConcurrencyType: When creating a managed object context with a
concurrency type of PrivateQueueConcurrencyType, the managed object context is
associated with a private queue and it can only be accessed from that private queue.
2.ConfinementConcurrencyType: Apple has deprecated this concurrency type as of
iOS 9. This is the concurrency type that corresponds with the thread
confinement concept . If you create a managed object context using init(), the
concurrency type of that managed object context is ConfinementConcurrencyType.
Fetching
Core Data Optimization
8
1. Use fetchBatchSize:
• This breaks the result set into batches. The entire request will be evaluated,
and the identities of all matching objects will be recorded, but no more than
batchSize objects' data will be fetched from the persistent store at a time.
• A batch size of 0 is treated as infinite, which disables the batch faulting
behavior.
let fetchRequest = NSFetchRequest(entityName: "DataEntity")
fetchRequest.sortDescriptors = [NSSortDescriptor(key:
UFO_KEY_COREDATA_SIGHTED, ascending: false)]
fetchRequest.fetchBatchSize = 20 //Set number double to visible cells
do
{
let test = try self.managedObjectContext.executeFetchRequest(fetchRequest) as Array
print("test count is: (test.count)")
}
catch let error as NSError
{
print("Error is : (error.localizedDescription)")
}
Fetching
Core Data Optimization
9
2. Use resultType: There are four types of result type
• ManagedObjectResultType
• ManagedObjectIDResultType
• DictionaryResultType
• CountResultType
let fetchRequest = NSFetchRequest(entityName: "DataEntity")
fetchRequest.resultType = .DictionaryResultType
do
{
let arrayOfFoundRecords = try
objAppDel.tempManagedObjectContext.executeFetchRequest(fetchRequest
}
catch let error as NSError
{
print("error in fetch is : (error.localizedDescription)")
}
Fetching
Core Data Optimization
10
3. Use NSExpressionDescription & NSExpression : Instances of
NSExpressionDescription objects represent a special property description type
intended for use with the NSFetchRequest PropertiesToFetch method. An
NSExpressionDescription describes a column to be returned from a fetch that may
not appear directly as an attribute or relationship on an entity. NSExpression is used
to represent expressions in a predicate. Comparison operations in an NSPredicate
are based on two expressions, as represented by instances of the NSExpression
class. Expressions are created for constant values, key paths etc.
//Create a expression
let expressionDescription = NSExpressionDescription()
expressionDescription.name = "count"
expressionDescription.expression = NSExpression(forFunction: "count:", arguments:
[NSExpression(forKeyPath: "shape")])
//Create a fetch Request
let fetchRequest = NSFetchRequest(entityName: "DataEntity")
Fetching
Core Data Optimization
11
3. Use GroupBy: Use groupBy to aggregate for same column name.
let fetchRequest = NSFetchRequest(entityName: "DataEntity")
fetchRequest.propertiesToGroupBy = ["shape"]
4. Use propertiesToFetch: create an array of properties you want to fetch from
CoreData.
let expressionDescription = NSExpressionDescription()
expressionDescription.name = "count”
expressionDescription.expression = NSExpression(forFunction: "count:", arguments:
[NSExpression(forKeyPath: "shape")])
//Create a fetch Request
let fetchRequest = NSFetchRequest(entityName: "DataEntity")
fetchRequest.propertiesToFetch = ["shape", expressionDescription]
Fetching
Core Data Optimization
12
5. PreFetch Any Required Relationship : Prefetching allows Core Data to obtain
developer-specified related objects in a single fetch.
let entityDescription = NSEntityDescription.entityForName("Employee",
inManagedObjectContext: self.managedObjectContext)
let fetchRequest = NSFetchRequest()
fetchRequest.entity = entityDescription
fetchRequest.relationshipKeyPathsForPrefetching = ["Department"]
do{
let arrayOfFoundRecords = try
self.managedObjectContext.executeFetchRequest(fetchRequest) as Array
for ( emp in arrayOfFoundRecords )
{
print("emp is: (emp)")
print("dept is: (emp.deptEmp)")
}
}
catch let error as NSError
{
}
Fetching
Core Data Optimization
13
Fetch Summary:
1.Don’t’ fetch anything that you don’t need.
2.Always use Batch Fetch.
3.Try to use NSExpressionDescription for Fetch in other word lets allow SQLite to do
calculation.
4.Use Prefeatch (relationshipKeyPathsForPrefetching) for required relationship.
Predicates:
Core Data Optimization
14
1. Light Predicate First: Always do String Comparison in last query. For example
fetchRequest.predicate = NSPredicate(format: "shape=%@ AND duration=%d", "circle", 30)
better way it to avoid string as much as possible or use string as a second argument.
So above code will perform better if we write it as:
fetchRequest.predicate = NSPredicate(format: "duration=%d shape=%@", 30, "circle”)
2. Use BeginsWith/EndsWith: Always try to use ‘beginsWith’ in creating a predicate.
Predicates:
Core Data Optimization
15
Predicate Summary & Cost Graph
1. Do light comparison first i.e. Numerical comparison.
2. Always try to use BeginsWith/EndsWith instead of Equals/Match.
3. Don’t/avoid to use CD in comparison.
Predicate
Cost
Less More
BeginsWith/
EndsWith
Equality
==
Contains
Matches
Search
Core Data Optimization
16
1. Always used Canonical String for search process. For example
String Canonical String
TEST test
åpple apple
Green Åpple green apple
2. Always use BeginsWith/EndsWith for searching.
Printing SQL Log
Core Data Optimization
17
Product menu by selecting “Manage Schemes” and then editing the current
scheme you are using. Select the “Run “phase and then select the “Arguments”
tab. Here you will see options to set arguments and environment variables. Add
-com.apple.CoreData.SQLDebug 3 to "Arguments Passed On Launch"
18
Thank you !

More Related Content

What's hot

Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
Ankur Dongre
 

What's hot (17)

Zend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching loggingZend framework 03 - singleton factory data mapper caching logging
Zend framework 03 - singleton factory data mapper caching logging
 
Jdbc oracle
Jdbc oracleJdbc oracle
Jdbc oracle
 
Core data orlando i os dev group
Core data   orlando i os dev groupCore data   orlando i os dev group
Core data orlando i os dev group
 
Client Server Communication on iOS
Client Server Communication on iOSClient Server Communication on iOS
Client Server Communication on iOS
 
Drools
DroolsDrools
Drools
 
iOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core DataiOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core Data
 
Underscore and Backbone Models
Underscore and Backbone ModelsUnderscore and Backbone Models
Underscore and Backbone Models
 
Spring frame work
Spring frame workSpring frame work
Spring frame work
 
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
【Unite 2017 Tokyo】ScriptableObjectを使ってプログラマーもアーティストも幸せになろう
 
Softshake - Offline applications
Softshake - Offline applicationsSoftshake - Offline applications
Softshake - Offline applications
 
Core Data with Swift 3.0
Core Data with Swift 3.0Core Data with Swift 3.0
Core Data with Swift 3.0
 
Advanced Core Data
Advanced Core DataAdvanced Core Data
Advanced Core Data
 
Spring data presentation
Spring data presentationSpring data presentation
Spring data presentation
 
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source Code
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source CodeUsing Fuzzy Code Search to Link Code Fragments in Discussions to Source Code
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source Code
 
Ejb3 Struts Tutorial En
Ejb3 Struts Tutorial EnEjb3 Struts Tutorial En
Ejb3 Struts Tutorial En
 
Struts2 - 101
Struts2 - 101Struts2 - 101
Struts2 - 101
 
KAAccessControl
KAAccessControlKAAccessControl
KAAccessControl
 

Viewers also liked

What have you learned from your audience feedback?
What have you learned from your audience feedback?What have you learned from your audience feedback?
What have you learned from your audience feedback?
Luke Randall
 
Simbolos de identificacion de la concentracion de desarrollo rural saravena a...
Simbolos de identificacion de la concentracion de desarrollo rural saravena a...Simbolos de identificacion de la concentracion de desarrollo rural saravena a...
Simbolos de identificacion de la concentracion de desarrollo rural saravena a...
Yeritza Neley Jimes Mejia
 

Viewers also liked (18)

Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central Dispatch
 
IBDesignable & IBInspectible
IBDesignable & IBInspectibleIBDesignable & IBInspectible
IBDesignable & IBInspectible
 
3Com 7030-10136
3Com 7030-101363Com 7030-10136
3Com 7030-10136
 
What have you learned from your audience feedback?
What have you learned from your audience feedback?What have you learned from your audience feedback?
What have you learned from your audience feedback?
 
プロジェクト
プロジェクトプロジェクト
プロジェクト
 
雷諾數測試與計算
雷諾數測試與計算雷諾數測試與計算
雷諾數測試與計算
 
Content Strategy Report: LPCS
Content Strategy Report: LPCSContent Strategy Report: LPCS
Content Strategy Report: LPCS
 
Cuidados de enfermería ante el accidente ofídico
Cuidados de enfermería ante el accidente ofídicoCuidados de enfermería ante el accidente ofídico
Cuidados de enfermería ante el accidente ofídico
 
Políticos [Maçonaria]
Políticos [Maçonaria]Políticos [Maçonaria]
Políticos [Maçonaria]
 
Рекламный буклет налоговой системы "Свободная экономика"
Рекламный буклет налоговой системы "Свободная экономика"Рекламный буклет налоговой системы "Свободная экономика"
Рекламный буклет налоговой системы "Свободная экономика"
 
Perfect places
Perfect placesPerfect places
Perfect places
 
Neibys Garcia
Neibys GarciaNeibys Garcia
Neibys Garcia
 
Poster1
Poster1Poster1
Poster1
 
Simbolos de identificacion de la concentracion de desarrollo rural saravena a...
Simbolos de identificacion de la concentracion de desarrollo rural saravena a...Simbolos de identificacion de la concentracion de desarrollo rural saravena a...
Simbolos de identificacion de la concentracion de desarrollo rural saravena a...
 
Presentacionrelacionespublicas 101125162209-phpapp02
Presentacionrelacionespublicas 101125162209-phpapp02Presentacionrelacionespublicas 101125162209-phpapp02
Presentacionrelacionespublicas 101125162209-phpapp02
 
Mejorar la usabilidad y la conversion con WPO en Wordpress
Mejorar la usabilidad y la conversion con WPO en WordpressMejorar la usabilidad y la conversion con WPO en Wordpress
Mejorar la usabilidad y la conversion con WPO en Wordpress
 
Creative critical reflection (short film) by Muhammad Hammaz
Creative critical reflection (short film) by Muhammad HammazCreative critical reflection (short film) by Muhammad Hammaz
Creative critical reflection (short film) by Muhammad Hammaz
 
CONÓCETE Y TE SORPRENDERÁS!
CONÓCETE Y TE SORPRENDERÁS!CONÓCETE Y TE SORPRENDERÁS!
CONÓCETE Y TE SORPRENDERÁS!
 

Similar to Core Data Performance Guide Line

Session 5 Tp5
Session 5 Tp5Session 5 Tp5
Session 5 Tp5
phanleson
 
Concurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background TasksConcurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background Tasks
WO Community
 
ASP.NET Session 11 12
ASP.NET Session 11 12ASP.NET Session 11 12
ASP.NET Session 11 12
Sisir Ghosh
 

Similar to Core Data Performance Guide Line (20)

Connecting to a REST API in iOS
Connecting to a REST API in iOSConnecting to a REST API in iOS
Connecting to a REST API in iOS
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
 
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
 
Simpler Core Data with RubyMotion
Simpler Core Data with RubyMotionSimpler Core Data with RubyMotion
Simpler Core Data with RubyMotion
 
Share point 2013 coding standards and best practices 1.0
Share point 2013 coding standards and best practices 1.0Share point 2013 coding standards and best practices 1.0
Share point 2013 coding standards and best practices 1.0
 
EMF Tips n Tricks
EMF Tips n TricksEMF Tips n Tricks
EMF Tips n Tricks
 
EJB Clients
EJB ClientsEJB Clients
EJB Clients
 
.NET Core, ASP.NET Core Course, Session 14
.NET Core, ASP.NET Core Course, Session 14.NET Core, ASP.NET Core Course, Session 14
.NET Core, ASP.NET Core Course, Session 14
 
Core Data
Core DataCore Data
Core Data
 
Session 5 Tp5
Session 5 Tp5Session 5 Tp5
Session 5 Tp5
 
Ruby on Rails Developer - Allerin
Ruby on Rails Developer - AllerinRuby on Rails Developer - Allerin
Ruby on Rails Developer - Allerin
 
[2 d1] elasticsearch 성능 최적화
[2 d1] elasticsearch 성능 최적화[2 d1] elasticsearch 성능 최적화
[2 d1] elasticsearch 성능 최적화
 
[2D1]Elasticsearch 성능 최적화
[2D1]Elasticsearch 성능 최적화[2D1]Elasticsearch 성능 최적화
[2D1]Elasticsearch 성능 최적화
 
Concurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background TasksConcurrency and Thread-Safe Data Processing in Background Tasks
Concurrency and Thread-Safe Data Processing in Background Tasks
 
ASP.NET Session 11 12
ASP.NET Session 11 12ASP.NET Session 11 12
ASP.NET Session 11 12
 
Scripting as a Second Language
Scripting as a Second LanguageScripting as a Second Language
Scripting as a Second Language
 
Data Binding in Silverlight
Data Binding in SilverlightData Binding in Silverlight
Data Binding in Silverlight
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
 
REST/JSON/CoreData Example Code - A Tour
REST/JSON/CoreData Example Code - A TourREST/JSON/CoreData Example Code - A Tour
REST/JSON/CoreData Example Code - A Tour
 
Real World MVC
Real World MVCReal World MVC
Real World MVC
 

More from Gagan Vishal Mishra

More from Gagan Vishal Mishra (8)

iOS Versions history
iOS Versions historyiOS Versions history
iOS Versions history
 
Core data optimization
Core data optimizationCore data optimization
Core data optimization
 
Jenkins CI/CD setup for iOS in Mac OSX
Jenkins CI/CD setup for iOS in Mac OSXJenkins CI/CD setup for iOS in Mac OSX
Jenkins CI/CD setup for iOS in Mac OSX
 
Linking between JIRA & GIT, Smart Commit Command
Linking between JIRA & GIT, Smart Commit Command Linking between JIRA & GIT, Smart Commit Command
Linking between JIRA & GIT, Smart Commit Command
 
Backbase CXP Manager Setup
Backbase CXP Manager SetupBackbase CXP Manager Setup
Backbase CXP Manager Setup
 
Dynamic databinding
Dynamic databindingDynamic databinding
Dynamic databinding
 
Visual Formatting Language in iOS
Visual Formatting Language in iOSVisual Formatting Language in iOS
Visual Formatting Language in iOS
 
Search API
Search APISearch API
Search API
 

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 

Core Data Performance Guide Line

  • 1. Core Data Optimization By Gagan Vishal Mishra
  • 2. Memory Vs. Performance Core Data Optimization 2 Memory Speed Less More Slow Faster
  • 3. Memory Vs. Performance Core Data Optimization 3 Memory Speed Less More Slow Faster
  • 4. Thread Safety In Core Data Core Data Optimization 4 • While working with Core Data, it's important to always remember that Core Data isn't thread safe. Core Data expects to be run on a single thread. • NSManagedObject, NSManagedObjectContext NSPersistentStoreCoordinator aren't thread safe. • This doesn't mean that every Core Data operation needs to be performed on the main thread, which is used for UI, but it means that we need to take care which operations are executed on which threads. We have to be careful how changes from one thread are propagated to other threads.
  • 5. Thread Safety In Core Data Core Data Optimization 5 1. NSManagedObject: NSManagedObject isn't thread safe but has an instance objectID that returns an instance of the NSManagedObjectID class which is thread safe. For getting do { let managedObject = try managedObjectContext.existingObjectWithID(objectID) } catch let fetchError as NSError { print("(fetchError), (fetchError.userInfo)”) } 2. NSManagedObjectContext: Isn't thread safe, we can create a managed object context for every thread that interacts with Core Data. This strategy is referred as thread confinement. A common approach is to create thread dictionary to store MOC. let currentThread = NSThread.currentThread() currentThread.threadDictionary.setObject(managedObjectContext, forKey: "managedObjectContext") 3. NSPersistentStoreCoordinator: We can create a separate persistent store coordinator for every thread. Which is also possible.
  • 6. Multithreading & Concurrency Strategies Core Data Optimization 6 The NSPersistentStoreCoordinator class was designed to support multiple managed object contexts, even if those managed object contexts were created on different threads. Because the NSManagedObjectContext class locks the persistent store coordinator while accessing it, it is possible for multiple managed object contexts to use the same persistent store coordinator even if those managed object contexts live on different threads. This makes a multithreaded Core Data setup much more manageable and less complex. There are two ways for Core Data Concurrency 1.Notifications 2.Parent/Child Managed Object Contexts Another option is 1.Independent Persistent Store Built with Notification & PrivateQueue
  • 7. Multithreading & Concurrency Strategies Core Data Optimization 7 There are three types of Concurrency options provided by Apple 1.MainQueueConcurrencyType: The managed object context is only accessible from the main thread. An exception is thrown if you try to access it from any other thread. 1.PrivateQueueConcurrencyType: When creating a managed object context with a concurrency type of PrivateQueueConcurrencyType, the managed object context is associated with a private queue and it can only be accessed from that private queue. 2.ConfinementConcurrencyType: Apple has deprecated this concurrency type as of iOS 9. This is the concurrency type that corresponds with the thread confinement concept . If you create a managed object context using init(), the concurrency type of that managed object context is ConfinementConcurrencyType.
  • 8. Fetching Core Data Optimization 8 1. Use fetchBatchSize: • This breaks the result set into batches. The entire request will be evaluated, and the identities of all matching objects will be recorded, but no more than batchSize objects' data will be fetched from the persistent store at a time. • A batch size of 0 is treated as infinite, which disables the batch faulting behavior. let fetchRequest = NSFetchRequest(entityName: "DataEntity") fetchRequest.sortDescriptors = [NSSortDescriptor(key: UFO_KEY_COREDATA_SIGHTED, ascending: false)] fetchRequest.fetchBatchSize = 20 //Set number double to visible cells do { let test = try self.managedObjectContext.executeFetchRequest(fetchRequest) as Array print("test count is: (test.count)") } catch let error as NSError { print("Error is : (error.localizedDescription)") }
  • 9. Fetching Core Data Optimization 9 2. Use resultType: There are four types of result type • ManagedObjectResultType • ManagedObjectIDResultType • DictionaryResultType • CountResultType let fetchRequest = NSFetchRequest(entityName: "DataEntity") fetchRequest.resultType = .DictionaryResultType do { let arrayOfFoundRecords = try objAppDel.tempManagedObjectContext.executeFetchRequest(fetchRequest } catch let error as NSError { print("error in fetch is : (error.localizedDescription)") }
  • 10. Fetching Core Data Optimization 10 3. Use NSExpressionDescription & NSExpression : Instances of NSExpressionDescription objects represent a special property description type intended for use with the NSFetchRequest PropertiesToFetch method. An NSExpressionDescription describes a column to be returned from a fetch that may not appear directly as an attribute or relationship on an entity. NSExpression is used to represent expressions in a predicate. Comparison operations in an NSPredicate are based on two expressions, as represented by instances of the NSExpression class. Expressions are created for constant values, key paths etc. //Create a expression let expressionDescription = NSExpressionDescription() expressionDescription.name = "count" expressionDescription.expression = NSExpression(forFunction: "count:", arguments: [NSExpression(forKeyPath: "shape")]) //Create a fetch Request let fetchRequest = NSFetchRequest(entityName: "DataEntity")
  • 11. Fetching Core Data Optimization 11 3. Use GroupBy: Use groupBy to aggregate for same column name. let fetchRequest = NSFetchRequest(entityName: "DataEntity") fetchRequest.propertiesToGroupBy = ["shape"] 4. Use propertiesToFetch: create an array of properties you want to fetch from CoreData. let expressionDescription = NSExpressionDescription() expressionDescription.name = "count” expressionDescription.expression = NSExpression(forFunction: "count:", arguments: [NSExpression(forKeyPath: "shape")]) //Create a fetch Request let fetchRequest = NSFetchRequest(entityName: "DataEntity") fetchRequest.propertiesToFetch = ["shape", expressionDescription]
  • 12. Fetching Core Data Optimization 12 5. PreFetch Any Required Relationship : Prefetching allows Core Data to obtain developer-specified related objects in a single fetch. let entityDescription = NSEntityDescription.entityForName("Employee", inManagedObjectContext: self.managedObjectContext) let fetchRequest = NSFetchRequest() fetchRequest.entity = entityDescription fetchRequest.relationshipKeyPathsForPrefetching = ["Department"] do{ let arrayOfFoundRecords = try self.managedObjectContext.executeFetchRequest(fetchRequest) as Array for ( emp in arrayOfFoundRecords ) { print("emp is: (emp)") print("dept is: (emp.deptEmp)") } } catch let error as NSError { }
  • 13. Fetching Core Data Optimization 13 Fetch Summary: 1.Don’t’ fetch anything that you don’t need. 2.Always use Batch Fetch. 3.Try to use NSExpressionDescription for Fetch in other word lets allow SQLite to do calculation. 4.Use Prefeatch (relationshipKeyPathsForPrefetching) for required relationship.
  • 14. Predicates: Core Data Optimization 14 1. Light Predicate First: Always do String Comparison in last query. For example fetchRequest.predicate = NSPredicate(format: "shape=%@ AND duration=%d", "circle", 30) better way it to avoid string as much as possible or use string as a second argument. So above code will perform better if we write it as: fetchRequest.predicate = NSPredicate(format: "duration=%d shape=%@", 30, "circle”) 2. Use BeginsWith/EndsWith: Always try to use ‘beginsWith’ in creating a predicate.
  • 15. Predicates: Core Data Optimization 15 Predicate Summary & Cost Graph 1. Do light comparison first i.e. Numerical comparison. 2. Always try to use BeginsWith/EndsWith instead of Equals/Match. 3. Don’t/avoid to use CD in comparison. Predicate Cost Less More BeginsWith/ EndsWith Equality == Contains Matches
  • 16. Search Core Data Optimization 16 1. Always used Canonical String for search process. For example String Canonical String TEST test åpple apple Green Åpple green apple 2. Always use BeginsWith/EndsWith for searching.
  • 17. Printing SQL Log Core Data Optimization 17 Product menu by selecting “Manage Schemes” and then editing the current scheme you are using. Select the “Run “phase and then select the “Arguments” tab. Here you will see options to set arguments and environment variables. Add -com.apple.CoreData.SQLDebug 3 to "Arguments Passed On Launch"

Editor's Notes

  1. http://www.cimgf.com/2015/06/25/core-data-and-aggregate-fetches-in-swift/ https://www.bignerdranch.com/blog/new-in-core-data-and-ios-8-batch-updating/
  2. http://www.cimgf.com/2015/06/25/core-data-and-aggregate-fetches-in-swift/ https://www.bignerdranch.com/blog/new-in-core-data-and-ios-8-batch-updating/
  3. http://www.cimgf.com/2015/06/25/core-data-and-aggregate-fetches-in-swift/ https://www.bignerdranch.com/blog/new-in-core-data-and-ios-8-batch-updating/
  4. http://www.cimgf.com/2015/06/25/core-data-and-aggregate-fetches-in-swift/ https://www.bignerdranch.com/blog/new-in-core-data-and-ios-8-batch-updating/
  5. http://www.cimgf.com/2015/06/25/core-data-and-aggregate-fetches-in-swift/ https://www.bignerdranch.com/blog/new-in-core-data-and-ios-8-batch-updating/
  6. http://www.cimgf.com/2015/06/25/core-data-and-aggregate-fetches-in-swift/ https://www.bignerdranch.com/blog/new-in-core-data-and-ios-8-batch-updating/
  7. http://www.cimgf.com/2015/06/25/core-data-and-aggregate-fetches-in-swift/ https://www.bignerdranch.com/blog/new-in-core-data-and-ios-8-batch-updating/
  8. http://www.cimgf.com/2015/06/25/core-data-and-aggregate-fetches-in-swift/ https://www.bignerdranch.com/blog/new-in-core-data-and-ios-8-batch-updating/
  9. http://www.cimgf.com/2015/06/25/core-data-and-aggregate-fetches-in-swift/ https://www.bignerdranch.com/blog/new-in-core-data-and-ios-8-batch-updating/