SlideShare une entreprise Scribd logo
1  sur  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 !

Contenu connexe

Tendances

( 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
 

Tendances (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
 

Similaire à 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
 

Similaire à 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 성능 최적화
 

Plus de Gagan Vishal Mishra

Plus de 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
 

Dernier

Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Skynet Technologies
 
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...ScyllaDB
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGDSC PJATK
 
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdfBreaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdfUK Journal
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxFIDO Alliance
 
Using IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandUsing IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandIES VE
 
TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024Stephen Perrenod
 
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...ScyllaDB
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe中 央社
 
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...FIDO Alliance
 
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The InsideCollecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The InsideStefan Dietze
 
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?Paolo Missier
 
Easier, Faster, and More Powerful – Notes Document Properties Reimagined
Easier, Faster, and More Powerful – Notes Document Properties ReimaginedEasier, Faster, and More Powerful – Notes Document Properties Reimagined
Easier, Faster, and More Powerful – Notes Document Properties Reimaginedpanagenda
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfFIDO Alliance
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...panagenda
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfFIDO Alliance
 
Your enemies use GenAI too - staying ahead of fraud with Neo4j
Your enemies use GenAI too - staying ahead of fraud with Neo4jYour enemies use GenAI too - staying ahead of fraud with Neo4j
Your enemies use GenAI too - staying ahead of fraud with Neo4jNeo4j
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024Lorenzo Miniero
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxFIDO Alliance
 

Dernier (20)

Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
 
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 Warsaw
 
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdfBreaking Down the Flutterwave Scandal What You Need to Know.pdf
Breaking Down the Flutterwave Scandal What You Need to Know.pdf
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
 
Using IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandUsing IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & Ireland
 
TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024TopCryptoSupers 12thReport OrionX May2024
TopCryptoSupers 12thReport OrionX May2024
 
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
 
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The InsideCollecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
Collecting & Temporal Analysis of Behavioral Web Data - Tales From The Inside
 
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
(Explainable) Data-Centric AI: what are you explaininhg, and to whom?
 
Easier, Faster, and More Powerful – Notes Document Properties Reimagined
Easier, Faster, and More Powerful – Notes Document Properties ReimaginedEasier, Faster, and More Powerful – Notes Document Properties Reimagined
Easier, Faster, and More Powerful – Notes Document Properties Reimagined
 
Overview of Hyperledger Foundation
Overview of Hyperledger FoundationOverview of Hyperledger Foundation
Overview of Hyperledger Foundation
 
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdfWhere to Learn More About FDO _ Richard at FIDO Alliance.pdf
Where to Learn More About FDO _ Richard at FIDO Alliance.pdf
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
 
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdfThe Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
The Value of Certifying Products for FDO _ Paul at FIDO Alliance.pdf
 
Your enemies use GenAI too - staying ahead of fraud with Neo4j
Your enemies use GenAI too - staying ahead of fraud with Neo4jYour enemies use GenAI too - staying ahead of fraud with Neo4j
Your enemies use GenAI too - staying ahead of fraud with Neo4j
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
Intro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptxIntro to Passkeys and the State of Passwordless.pptx
Intro to Passkeys and the State of Passwordless.pptx
 

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"

Notes de l'éditeur

  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/