SlideShare a Scribd company logo
1 of 18
Core Data Optimization
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

( 15 ) Office 2007 Create A Membership Database
( 15 ) Office 2007   Create A Membership Database( 15 ) Office 2007   Create A Membership Database
( 15 ) Office 2007 Create A Membership DatabaseLiquidHub
 
บทที่ 3 การเขียนโปรแกรมติดต่อฐานข้อมูล
บทที่ 3 การเขียนโปรแกรมติดต่อฐานข้อมูลบทที่ 3 การเขียนโปรแกรมติดต่อฐานข้อมูล
บทที่ 3 การเขียนโปรแกรมติดต่อฐานข้อมูลPriew Chakrit
 
Tutorial windows service with java (procrun)
Tutorial windows service with java (procrun)Tutorial windows service with java (procrun)
Tutorial windows service with java (procrun)muhammad arif nasution
 
Oracle to MySQL DatabaseLink
Oracle to MySQL DatabaseLinkOracle to MySQL DatabaseLink
Oracle to MySQL DatabaseLinkOsama Mustafa
 
Why Task Queues - ComoRichWeb
Why Task Queues - ComoRichWebWhy Task Queues - ComoRichWeb
Why Task Queues - ComoRichWebBryan Helmig
 
Beginner guide to mysql command line
Beginner guide to mysql command lineBeginner guide to mysql command line
Beginner guide to mysql command linePriti Solanki
 

What's hot (17)

Sql installation
Sql installationSql installation
Sql installation
 
Nodejs Session01
Nodejs Session01Nodejs Session01
Nodejs Session01
 
( 15 ) Office 2007 Create A Membership Database
( 15 ) Office 2007   Create A Membership Database( 15 ) Office 2007   Create A Membership Database
( 15 ) Office 2007 Create A Membership Database
 
บทที่ 3 การเขียนโปรแกรมติดต่อฐานข้อมูล
บทที่ 3 การเขียนโปรแกรมติดต่อฐานข้อมูลบทที่ 3 การเขียนโปรแกรมติดต่อฐานข้อมูล
บทที่ 3 การเขียนโปรแกรมติดต่อฐานข้อมูล
 
ExpressJs Session01
ExpressJs Session01ExpressJs Session01
ExpressJs Session01
 
Oracle WebLogic
Oracle WebLogicOracle WebLogic
Oracle WebLogic
 
Mule esb :Data Weave
Mule esb :Data WeaveMule esb :Data Weave
Mule esb :Data Weave
 
Tutorial windows service with java (procrun)
Tutorial windows service with java (procrun)Tutorial windows service with java (procrun)
Tutorial windows service with java (procrun)
 
154090896 installation-of-oracle-database-12c
154090896 installation-of-oracle-database-12c154090896 installation-of-oracle-database-12c
154090896 installation-of-oracle-database-12c
 
Dbm 438 week 6 ilab
Dbm 438 week 6 ilabDbm 438 week 6 ilab
Dbm 438 week 6 ilab
 
Knowledge article
Knowledge articleKnowledge article
Knowledge article
 
Oracle to MySQL DatabaseLink
Oracle to MySQL DatabaseLinkOracle to MySQL DatabaseLink
Oracle to MySQL DatabaseLink
 
Why Task Queues - ComoRichWeb
Why Task Queues - ComoRichWebWhy Task Queues - ComoRichWeb
Why Task Queues - ComoRichWeb
 
Beginner guide to mysql command line
Beginner guide to mysql command lineBeginner guide to mysql command line
Beginner guide to mysql command line
 
PowerShell-2
PowerShell-2PowerShell-2
PowerShell-2
 
NodeJs Session02
NodeJs Session02NodeJs Session02
NodeJs Session02
 
Dspace
DspaceDspace
Dspace
 

Similar to Core data optimization

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 iOSgillygize
 
Core Data with multiple managed object contexts
Core Data with multiple managed object contextsCore Data with multiple managed object contexts
Core Data with multiple managed object contextsMatthew Morey
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core DataMake School
 
Core Data with Swift 3.0
Core Data with Swift 3.0Core Data with Swift 3.0
Core Data with Swift 3.0Korhan Bircan
 
iOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core DataiOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core DataChris Mar
 
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 groupAndrew Kozlik
 
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...smn-automate
 
Simpler Core Data with RubyMotion
Simpler Core Data with RubyMotionSimpler Core Data with RubyMotion
Simpler Core Data with RubyMotionStefan Haflidason
 
Advanced Hibernate Notes
Advanced Hibernate NotesAdvanced Hibernate Notes
Advanced Hibernate NotesKaniska Mandal
 
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.0LiquidHub
 
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 loggingTricode (part of Dept)
 
Session 5 Tp5
Session 5 Tp5Session 5 Tp5
Session 5 Tp5phanleson
 
Ruby on Rails Developer - Allerin
Ruby on Rails Developer - AllerinRuby on Rails Developer - Allerin
Ruby on Rails Developer - AllerinLauree R
 
.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 14aminmesbahi
 
Data Binding in Silverlight
Data Binding in SilverlightData Binding in Silverlight
Data Binding in SilverlightBoulos Dib
 
[2 d1] elasticsearch 성능 최적화
[2 d1] elasticsearch 성능 최적화[2 d1] elasticsearch 성능 최적화
[2 d1] elasticsearch 성능 최적화Henry Jeong
 

Similar to Core data optimization (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
 
Core Data with multiple managed object contexts
Core Data with multiple managed object contextsCore Data with multiple managed object contexts
Core Data with multiple managed object contexts
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
 
Core Data with Swift 3.0
Core Data with Swift 3.0Core Data with Swift 3.0
Core Data with Swift 3.0
 
iOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core DataiOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core Data
 
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
 
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
 
EMF Tips n Tricks
EMF Tips n TricksEMF Tips n Tricks
EMF Tips n Tricks
 
Advanced Hibernate Notes
Advanced Hibernate NotesAdvanced Hibernate Notes
Advanced Hibernate Notes
 
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
 
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
 
Session 5 Tp5
Session 5 Tp5Session 5 Tp5
Session 5 Tp5
 
Core Data
Core DataCore Data
Core Data
 
EJB Clients
EJB ClientsEJB Clients
EJB Clients
 
Ruby on Rails Developer - Allerin
Ruby on Rails Developer - AllerinRuby on Rails Developer - Allerin
Ruby on Rails Developer - Allerin
 
.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
 
Data Binding in Silverlight
Data Binding in SilverlightData Binding in Silverlight
Data Binding in Silverlight
 
Real World MVC
Real World MVCReal World MVC
Real World MVC
 
[2 d1] elasticsearch 성능 최적화
[2 d1] elasticsearch 성능 최적화[2 d1] elasticsearch 성능 최적화
[2 d1] elasticsearch 성능 최적화
 

More from Gagan Vishal Mishra

More from Gagan Vishal Mishra (8)

iOS Versions history
iOS Versions historyiOS Versions history
iOS Versions history
 
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
 
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
 
IBDesignable & IBInspectible
IBDesignable & IBInspectibleIBDesignable & IBInspectible
IBDesignable & IBInspectible
 
Core Data Performance Guide Line
Core Data Performance Guide LineCore Data Performance Guide Line
Core Data Performance Guide Line
 

Recently uploaded

Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
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 organizationRadu Cotescu
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 

Recently uploaded (20)

Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
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
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 

Core data optimization

  • 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/