+ All Categories
Home > Documents > Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank...

Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank...

Date post: 22-Jun-2020
Category:
Upload: others
View: 0 times
Download: 0 times
Share this document with a friend
222
These are confidential sessions—please refrain from streaming, blogging, or taking pictures Choosing and using data structures effectively Session 224 Designing Code for Performance Quinn Taylor Internal Applications Engineer
Transcript
Page 1: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

These are confidential sessions—please refrain from streaming, blogging, or taking pictures

Choosing and using data structures effectively

Session 224

Designing Code for Performance

Quinn TaylorInternal Applications Engineer

Page 2: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Introduction

Page 3: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Introduction

•Huge influx of new developers

Page 4: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Introduction

•Huge influx of new developers•Diverse backgrounds and experience

Page 5: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Introduction

•Huge influx of new developers•Diverse backgrounds and experience•Data structures performance issues are universal

Page 6: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Introduction

•Huge influx of new developers•Diverse backgrounds and experience•Data structures performance issues are universal• Puzzling unless you know what’s going on under the hood

Page 7: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

“Give a man a fish and you feed him for a day. Teach a man how to fish and you feed him for a lifetime.”

Chinese Proverb

Page 8: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

What You Will Learn

Page 9: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

What You Will Learn

•When to focus on performance

Page 10: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

What You Will Learn

•When to focus on performance•How to evaluate computational complexity

Page 11: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

What You Will Learn

•When to focus on performance•How to evaluate computational complexity•How to choose and use data structures

Page 12: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

What You Will Learn

•When to focus on performance•How to evaluate computational complexity•How to choose and use data structures•How to design your code for performance

Page 13: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

When to Focus on Performance

Page 14: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

“We don’t get a chance to do that many things, and every one should be really excellent. …[W]e’ve all chosen to do this with our lives.So it better be damn good.It better be worth it.”Steve Jobs (2008)

Page 15: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

“You have to pick carefully. Innovation is saying no to 1,000 things.”

Steve Jobs (1997)

Page 16: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

“We should forget about small efficiencies ... about 97% of the time. Premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.”Donald Knuth (1974)

Page 17: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

“We should forget about small efficiencies ... about 97% of the time. Premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.”Donald Knuth (1974)

Page 18: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

“Optimize performance when itwill make a meaningful difference.”

Me (just now)

Page 19: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Amdahl’s LawPicking Your Battles

Page 20: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Amdahl’s LawPicking Your Battles

•Maximum improvement from speeding up code■ Depends on percentage of execution time■ Payoff is bigger for dominant pieces

Page 21: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Amdahl’s LawPicking Your Battles

•Maximum improvement from speeding up code■ Depends on percentage of execution time■ Payoff is bigger for dominant pieces

•Will the payoff be worth the effort?

Page 22: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Amdahl’s LawPicking Your Battles

•Maximum improvement from speeding up code■ Depends on percentage of execution time■ Payoff is bigger for dominant pieces

•Will the payoff be worth the effort?•Applies directly to concurrency

Page 23: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Amdahl’s Law examplePicking Your Battles

Page 24: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Amdahl’s Law examplePicking Your Battles

Original

Make B 2x Faster

Make A 2x Faster

A B

Page 25: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Amdahl’s Law examplePicking Your Battles

Original

Make B 2x Faster

Make A 2x Faster

2080

A B

Page 26: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Amdahl’s Law examplePicking Your Battles

Original

Make B 2x Faster

Make A 2x Faster

2080

1080

A B

Page 27: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Amdahl’s Law examplePicking Your Battles

Original

Make B 2x Faster

Make A 2x Faster

2080

1080

2040

A B

Page 28: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Premature Optimization vs. Informed Design

Page 29: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Premature Optimization vs. Informed Design

• Premature optimization leads to unnecessary complexity■ “If it ain’t broke, don’t fix it.”■ Use Instruments to focus on bottlenecks

Page 30: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Premature Optimization vs. Informed Design

• Premature optimization leads to unnecessary complexity■ “If it ain’t broke, don’t fix it.”■ Use Instruments to focus on bottlenecks

• Informed design leads to elegant, efficient code■ Consider performance during design■ Intelligently avoid real performance pitfalls■ Why design in slowness you can easily avoid?

Page 31: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

How to Design for Performance

Page 32: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

How to Design for Performance

• Resolving a performance issue■ Don’t do it■ Do it as rarely as possible■ Do it as efficiently as possible

Page 33: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

How to Design for Performance

• Resolving a performance issue■ Don’t do it■ Do it as rarely as possible■ Do it as efficiently as possible

• Improvement requires context■ Is this work necessary?■ Is redundant work being done?■ Is there a more efficient way?

Page 34: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

How do I know if I can do better?

Page 35: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Computational Complexity and Cost

Page 36: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

The Cost of Code

Page 37: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

The Cost of Code

• Code takes time to run■ More work takes more time■ Short code may be work-intensive

Page 38: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

The Cost of Code

• Code takes time to run■ More work takes more time■ Short code may be work-intensive

• Effects of data growth can vary dramatically■ Work may grow disproportionately■ Small tests won’t reveal scaling problems

Page 39: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

The Cost of Code

• Code takes time to run■ More work takes more time■ Short code may be work-intensive

• Effects of data growth can vary dramatically■ Work may grow disproportionately■ Small tests won’t reveal scaling problems

• Can be analyzed even without running code■ Understanding algorithm complexity is key■ Computer Science has entire courses about this

Page 40: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Complexity and “Big O” Notation

Page 41: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Complexity and “Big O” Notation

• Rank algorithms by efficiency (time, memory, etc.)■ The letter “O” represents the order (growth rate) ■ Performance change as scale increases

Page 42: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Complexity and “Big O” Notation

• Rank algorithms by efficiency (time, memory, etc.)■ The letter “O” represents the order (growth rate) ■ Performance change as scale increases

• “Big O” approximates worst case■ Ignore coefficients and lower-order terms (e.g. 6n2+3n+2 ≈ n2)■ Ignore logarithm bases (e.g. log10n ≈ log2n ≈ log n)

Page 43: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Complexity and “Big O” Notation

• Rank algorithms by efficiency (time, memory, etc.)■ The letter “O” represents the order (growth rate) ■ Performance change as scale increases

• “Big O” approximates worst case■ Ignore coefficients and lower-order terms (e.g. 6n2+3n+2 ≈ n2)■ Ignore logarithm bases (e.g. log10n ≈ log2n ≈ log n)

• For any given task, there are inherent limits■ Some things just take time

Page 44: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

“Nine women can’tmake a baby in one month.”

Fred Brooks — “The Mythical Man-Month” (1975)

Page 45: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Order functions“Big O” Complexity

Page 46: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Order functions“Big O” Complexity

Notation Name Examples

O(1) constant time simple expressions,indexed/hashed lookup

O(log n) logarithmic time search of sorted data

O(n) linear time search of unsorted data,enumeration, “for each” loop

O(n log n) log-linear time efficient sorting algorithms

O(n2) quadratic time nested iteration of data

O(cn) exponential time combinatorial explosion,high-dimensional data

Page 47: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Order functions“Big O” Complexity

• Some are much more common

Notation Name Examples

O(1) constant time simple expressions,indexed/hashed lookup

O(log n) logarithmic time search of sorted data

O(n) linear time search of unsorted data,enumeration, “for each” loop

O(n log n) log-linear time efficient sorting algorithms

O(n2) quadratic time nested iteration of data

O(cn) exponential time combinatorial explosion,high-dimensional data

Page 48: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Order functions comparison“Big O” Complexity

Page 49: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Order functions comparison

Ope

ratio

ns /

Tim

e

Items

O(n^2)O(n log n)O(n)O(log n)O(1)

“Big O” Complexity

Page 50: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Order functions comparison

Ope

ratio

ns /

Tim

e

Items

O(n^2)O(n log n)O(n)O(log n)O(1)

“Big O” Complexity

Page 51: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Order functions comparison

Ope

ratio

ns /

Tim

e

Items

O(n^2)O(n log n)O(n)O(log n)O(1)

“Big O” Complexity

Page 52: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Order functions comparison

Ope

ratio

ns /

Tim

e

Items

O(n^2)O(n log n)O(n)O(log n)O(1)

“Big O” Complexity

Page 53: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Order functions comparison

Ope

ratio

ns /

Tim

e

Items

O(n^2)O(n log n)O(n)O(log n)O(1)

“Big O” Complexity

Page 54: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Order functions comparison

Ope

ratio

ns /

Tim

e

Items

O(n^2)O(n log n)O(n)O(log n)O(1)

“Big O” Complexity

Page 55: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Examples

•Determine complexity from source code•Growth of work with size is key

“Big O” Complexity

Page 56: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Example: O(1)

BOOL ContainsValueAtIndex(int[] array, int count, int value, int idx) { return (idx < count && array[idx] == value);}

“Big O” Complexity

Page 57: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Example: O(1)

BOOL ContainsValueAtIndex(int[] array, int count, int value, int idx) { return (idx < count && array[idx] == value);}

“Big O” Complexity

Page 58: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Example: O(1)

BOOL ContainsValueAtIndex(int[] array, int count, int value, int idx) { return (idx < count && array[idx] == value);}

idx

“Big O” Complexity

Page 59: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Example: O(1)

BOOL ContainsValueAtIndex(int[] array, int count, int value, int idx) { return (idx < count && array[idx] == value);}

idx

“Big O” Complexity

Page 60: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Example: O(1)

BOOL ContainsValueAtIndex(int[] array, int count, int value, int idx) { return (idx < count && array[idx] == value);}

idx

“Big O” Complexity

Page 61: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Example: O(1)

BOOL ContainsValueAtIndex(int[] array, int count, int value, int idx) { return (idx < count && array[idx] == value);}

“Big O” Complexity

Page 62: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Example: O(n)

BOOL ContainsValue(int[] array, int count, int value) { for (int i = 0; i < count; i++) { // O(n) if (array[i] == value) { return YES; } } return NO;}

?=

“Big O” Complexity

Page 63: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Example: O(n)

BOOL ContainsValue(int[] array, int count, int value) { for (int i = 0; i < count; i++) { // O(n) if (array[i] == value) { return YES; } } return NO;}

?=

“Big O” Complexity

Page 64: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Example: O(n2)

BOOL ContainsDuplicateValues(int[] array, int count) { for (int i = 0; i < count; i++) { // O(n) for (int j = 0; j < count; j++) { // O(n) if (i != j && array[i] == array[j]) { return YES; } } } return NO;}

“Big O” Complexity

Page 65: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Example: O(n2)

BOOL ContainsDuplicateValues(int[] array, int count) { for (int i = 0; i < count; i++) { // O(n) for (int j = 0; j < count; j++) { // O(n) if (i != j && array[i] == array[j]) { return YES; } } } return NO;}

ij

“Big O” Complexity

Page 66: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Example: O(n2)

BOOL ContainsDuplicateValues(int[] array, int count) { for (int i = 0; i < count; i++) { // O(n) for (int j = 0; j < count; j++) { // O(n) if (i != j && array[i] == array[j]) { return YES; } } } return NO;}

“Big O” Complexity

Page 67: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Calculating Complexity

Page 68: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Calculating Complexity

•Order functions can be combined■ Multiply nested complexities■ Add sequential complexities

Page 69: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Calculating Complexity

•Order functions can be combined■ Multiply nested complexities■ Add sequential complexities

• This function reduces to O(n2) void AnalyzeArray(int[] array, int count) { ContainsDuplicateValues(array, count); // O(n^2) ContainsValue(array, count, 0); // O(n) ContainsValue(array, count, 1); // O(n) ContainsValueAtIndex(array, count, 1, 0); // O(1) ContainsValueAtIndex(array, count, 0, 1); // O(1) ContainsValueAtIndex(array, count, 1, 1); // O(1) }

Page 70: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Estimating Complexity

Page 71: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Estimating Complexity

•When you don’t know, estimate■ Consider what the code does■ Profile with Instruments

Page 72: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Estimating Complexity

•When you don’t know, estimate■ Consider what the code does■ Profile with Instruments

• Some APIs appear similar, but don’t assume■ For example, -containsObject: on NSArray and NSSet

Page 73: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Reading between the linesEstimating Complexity

Page 74: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Reading between the linesEstimating Complexity

• Consider -[NSArray containsObject:]■ What does it do?■ Documentation says it sends -isEqual: to each object

Page 75: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Reading between the linesEstimating Complexity

• Consider -[NSArray containsObject:]■ What does it do?■ Documentation says it sends -isEqual: to each object

• This sounds like O(n)

Page 76: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Reading between the linesEstimating Complexity

• Consider -[NSArray containsObject:]■ What does it do?■ Documentation says it sends -isEqual: to each object

• This sounds like O(n)• Concurrency would only reduce by some factor

Page 77: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Jumping to the wrong conclusionEstimating Complexity

Page 78: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Jumping to the wrong conclusionEstimating Complexity

• Consider -[NSSet containsObject:]

Page 79: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Jumping to the wrong conclusionEstimating Complexity

• Consider -[NSSet containsObject:]• It looks just like -[NSArray containsObject:]

Page 80: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Jumping to the wrong conclusionEstimating Complexity

• Consider -[NSSet containsObject:]• It looks just like -[NSArray containsObject:]• Is it also O(n)?

Tim

e

Objects

Page 81: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Jumping to the wrong conclusionEstimating Complexity

• Consider -[NSSet containsObject:]• It looks just like -[NSArray containsObject:]• Is it also O(n)?• It’s actually O(1)

Tim

e

Objects

Page 82: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Jumping to the wrong conclusionEstimating Complexity

• Consider -[NSSet containsObject:]• It looks just like -[NSArray containsObject:]• Is it also O(n)?• It’s actually O(1)• It must do less work

Tim

e

Objects

Page 83: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Hash-Based Organization

Page 84: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Hash-Based Organization

•NSSet uses a hash table for storage

Page 85: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Hash-Based Organization

•NSSet uses a hash table for storage•Objects have a deterministic hash value

■ -hash returns an NSUInteger■ Equal objects have the same hash

Page 86: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Hash-Based Organization

•NSSet uses a hash table for storage•Objects have a deterministic hash value

■ -hash returns an NSUInteger■ Equal objects have the same hash

•Objects are grouped in “buckets”■ A hash function maps hashes to buckets■ Goal is uniform distribution

Page 87: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Hash-Based Organization

•NSSet uses a hash table for storage•Objects have a deterministic hash value

■ -hash returns an NSUInteger■ Equal objects have the same hash

•Objects are grouped in “buckets”■ A hash function maps hashes to buckets■ Goal is uniform distribution

• Lookup only considers objects in one bucket■ Check -isEqual: for very few objects (or none)

Page 88: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Hash-Based Organization

Hash Function Buckets

0

1

2

3

4

5

Page 89: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Hash-Based Organization

Hash Function Buckets

0

1

2

3

4

5

@"Tim Cook"

Page 90: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Hash-Based Organization

Hash Function Buckets

0

1

2

3

4

5

@"Tim Cook"

@"Tim Cook"

Page 91: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Hash-Based Organization

Hash Function Buckets

0

1

2

3

4

5

@"Tim Cook"

@"Steve Jobs"

@"Tim Cook"

@"Steve Jobs"

Page 92: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Hash-Based Organization

Hash Function Buckets

0

1

2

3

4

5

@"Tim Cook"

@"Steve Jobs"

@"Gil Amelio"@"Tim Cook"

@"Steve Jobs"

Page 93: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Hash-Based Organization

Hash Function Buckets

0

1

2

3

4

5

@"Tim Cook"

@"Steve Jobs"

@"Gil Amelio"@"Tim Cook"

@"Steve Jobs"

Page 94: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Hash-Based Organization

Hash Function Buckets

0

1

2

3

4

5

@"Tim Cook"

@"Steve Jobs"

@"Gil Amelio"@"Tim Cook"

@"Steve Jobs"@"Gil Amelio"

Page 95: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Hash-Based Organization

Hash Function Buckets

0

1

2

3

4

5

@"Tim Cook"

@"Steve Jobs"

@"Gil Amelio"

@"Michael Spindler"

@"Tim Cook"

@"Steve Jobs"

@"Michael Spindler"

@"Gil Amelio"

Page 96: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Hash-Based Organization

Hash Function Buckets

0

1

2

3

4

5

@"Tim Cook"

@"Steve Jobs"

@"Gil Amelio"

@"Michael Spindler"

@"John Sculley"

@"Tim Cook"

@"Steve Jobs"

@"Michael Spindler"

@"Gil Amelio"

Page 97: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Hash-Based Organization

Hash Function Buckets

0

1

2

3

4

5

@"Tim Cook"

@"Steve Jobs"

@"Gil Amelio"

@"Michael Spindler"

@"John Sculley"

@"Tim Cook"

@"Steve Jobs"

@"Michael Spindler"

@"Gil Amelio"

Page 98: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Hash-Based Organization

Hash Function Buckets

0

1

2

3

4

5

@"Tim Cook"

@"Steve Jobs"

@"Gil Amelio"

@"Michael Spindler"

@"John Sculley"

@"Tim Cook"

@"Steve Jobs"

@"Michael Spindler"

@"Gil Amelio"@"John Sculley"

Page 99: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Hash-Based Organization

Hash Function Buckets

0

1

2

3

4

5

@"Tim Cook"

@"Steve Jobs"

@"Gil Amelio"

@"Michael Spindler"

@"John Sculley"

@"Tim Cook"

@"Steve Jobs"

@"Michael Spindler"

@"Gil Amelio"@"John Sculley"

@”Bill Gates”?

Page 100: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Hash-Based Organization

Hash Function Buckets

0

1

2

3

4

5

@"Tim Cook"

@"Steve Jobs"

@"Gil Amelio"

@"Michael Spindler"

@"John Sculley"

@"Tim Cook"

@"Steve Jobs"

@"Michael Spindler"

@"Gil Amelio"@"John Sculley"

@”Bill Gates”?

Page 101: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Hash-Based Organization

Hash Function Buckets

0

1

2

3

4

5

@"Tim Cook"

@"Steve Jobs"

@"Gil Amelio"

@"Michael Spindler"

@"John Sculley"

@"Tim Cook"

@"Steve Jobs"

@"Michael Spindler"

@"Gil Amelio"@"John Sculley"

@”Bill Gates”?

Page 102: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Hash-Based Organization

Hash Function Buckets

0

1

2

3

4

5

@"Tim Cook"

@"Steve Jobs"

@"Gil Amelio"

@"Michael Spindler"

@"John Sculley"

@"Tim Cook"

@"Steve Jobs"

@"Michael Spindler"

@"Gil Amelio"@"John Sculley"

Page 103: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Hash-Based Organization

Hash Function Buckets

0

1

2

3

4

5

@"Tim Cook"

@"Steve Jobs"

@"Gil Amelio"

@"Michael Spindler"

@"John Sculley"

@"Tim Cook"

@"Steve Jobs"

@"Michael Spindler"

@"Gil Amelio"

@"John Sculley"

Page 104: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Define your identityHash-Based Organization

Page 105: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Define your identityHash-Based Organization

•NSObject’s -isEqual: and -hash are functionally equivalent to: - (BOOL) isEqual:(id)other { return self == other; } - (NSUInteger) hash { return (NSUInteger)self; }

Page 106: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Define your identityHash-Based Organization

•NSObject’s -isEqual: and -hash are functionally equivalent to: - (BOOL) isEqual:(id)other { return self == other; } - (NSUInteger) hash { return (NSUInteger)self; }

•Apple-provided subclasses override as needed

Page 107: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Define your identityHash-Based Organization

•NSObject’s -isEqual: and -hash are functionally equivalent to: - (BOOL) isEqual:(id)other { return self == other; } - (NSUInteger) hash { return (NSUInteger)self; }

•Apple-provided subclasses override as needed • Custom objects should override if pointer equality is not enough

Page 108: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Define your identityHash-Based Organization

•NSObject’s -isEqual: and -hash are functionally equivalent to: - (BOOL) isEqual:(id)other { return self == other; } - (NSUInteger) hash { return (NSUInteger)self; }

•Apple-provided subclasses override as needed • Custom objects should override if pointer equality is not enough• http://developer.apple.com/documentation/General/Conceptual/DevPedia-CocoaCore/ObjectComparison.html

Page 109: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Rules of the roadHash-Based Organization

Page 110: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Rules of the roadHash-Based Organization

• If -isEqual: returns true, -hash must be equal for both objects■ The same hash value does not imply equality

Page 111: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Rules of the roadHash-Based Organization

• If -isEqual: returns true, -hash must be equal for both objects■ The same hash value does not imply equality

• If you define -isEqual:, also define -hash

Page 112: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Rules of the roadHash-Based Organization

• If -isEqual: returns true, -hash must be equal for both objects■ The same hash value does not imply equality

• If you define -isEqual:, also define -hash•A good hash should minimize collisions

■ Poor hashes will degrade performance

Page 113: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Rules of the roadHash-Based Organization

• If -isEqual: returns true, -hash must be equal for both objects■ The same hash value does not imply equality

• If you define -isEqual:, also define -hash•A good hash should minimize collisions

■ Poor hashes will degrade performance

•Hash lookup + unpredictable hash = disaster■ Option 1: Don’t modify object in a collection■ Option 2: Don’t base hash on mutable state

Page 114: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Sample implementationHash-Based Organization

@interface WWDCNews : NSObject <NSCopying>@property (readonly, copy) NSString *title;@property (readonly, copy) NSDate *timestamp;@end

@implementation WWDCNews- (NSUInteger) hash { return [self.title hash];}

- (BOOL) isEqual:(id)object { return ([object isKindOfClass:[WWDCNews class]] && [self.title isEqual:[object title]] && [self.timestamp isEqual:[object timestamp]]);}...@end

Page 115: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Sample implementationHash-Based Organization

@interface WWDCNews : NSObject <NSCopying>@property (readonly, copy) NSString *title;@property (readonly, copy) NSDate *timestamp;@end

@implementation WWDCNews- (NSUInteger) hash { return [self.title hash];}

- (BOOL) isEqual:(id)object { return ([object isKindOfClass:[WWDCNews class]] && [self.title isEqual:[object title]] && [self.timestamp isEqual:[object timestamp]]);}...@end

Page 116: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Data Structures Performance

Page 117: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Choosing a strategyExample: Organizing Books

Page 118: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

• Sort by topic, author, title, size, color, etc.

Choosing a strategyExample: Organizing Books

Page 119: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

• Sort by topic, author, title, size, color, etc.• Each option makes some tasks easy, other tasks hard

Choosing a strategyExample: Organizing Books

Page 120: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

• Sort by topic, author, title, size, color, etc.• Each option makes some tasks easy, other tasks hard• Plan for scale when appropriate

Choosing a strategyExample: Organizing Books

Page 121: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

• Sort by topic, author, title, size, color, etc.• Each option makes some tasks easy, other tasks hard• Plan for scale when appropriate

Choosing a strategyExample: Organizing Books

Page 122: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

• Sort by topic, author, title, size, color, etc.• Each option makes some tasks easy, other tasks hard• Plan for scale when appropriate

Choosing a strategyExample: Organizing Books

Page 123: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Choosing a strategyData Structures Performance

Page 124: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

•All data structures have tradeoffs■ Use one that best fits your needs

Choosing a strategyData Structures Performance

Page 125: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

•All data structures have tradeoffs■ Use one that best fits your needs

•A bad fit hurts performance■ The wrong tool■ The wrong approach

Choosing a strategyData Structures Performance

Page 126: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

•All data structures have tradeoffs■ Use one that best fits your needs

•A bad fit hurts performance■ The wrong tool■ The wrong approach

•Always prefer to use the built-in API■ Extensively tested and optimized■ Automatic future improvements

Choosing a strategyData Structures Performance

Page 127: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Context is keyData Structures

Page 128: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Context is keyData Structures

• Know what you need■ Is order important?■ Will I have duplicates?■ Is mutability required?■ What operations are most critical?■ Where will data come from and go to?

Page 129: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Context is keyData Structures

• Know what you need■ Is order important?■ Will I have duplicates?■ Is mutability required?■ What operations are most critical?■ Where will data come from and go to?

• Know what to expect■ Getting the count is O(1)■ Enumerating all objects is O(n)■ Other operations vary by collection

Page 130: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Mutability

Page 131: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Mutability

•Use it when you need it

Page 132: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Mutability

•Use it when you need it• Immutable collections have benefits

■ Thread safety■ Memory and speed optimizations

Page 133: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Mutability

•Use it when you need it• Immutable collections have benefits

■ Thread safety■ Memory and speed optimizations

•Make immutable copy afterward?

Page 134: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Mutability

•Use it when you need it• Immutable collections have benefits

■ Thread safety■ Memory and speed optimizations

•Make immutable copy afterward?•Help us help you

■ You know how it will be used■ Hints can enhance performance■ Consider using -initWithCapacity:

Page 135: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Foundation Collection MVPs

•NSArray / NSMutableArray•NSSet / NSMutableSet / NSCountedSet•NSDictionary / NSMutableDictionary•NSOrderedSet / NSMutableOrderedSet•NSIndexSet / NSMutableIndexSet•NSMapTable•NSHashTable•NSCache

Page 136: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSArray / NSMutableArray

Page 137: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSArray / NSMutableArray

•Ordered, indexed, allows duplicates

Page 138: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSArray / NSMutableArray

•Ordered, indexed, allows duplicates• Fast operations

■ Indexed access (e.g. -objectAtIndex:, -firstObject, -lastObject)■ Add / remove at either end (e.g. -addObject:, -removeLastObject:)

Page 139: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSArray / NSMutableArray

•Ordered, indexed, allows duplicates• Fast operations

■ Indexed access (e.g. -objectAtIndex:, -firstObject, -lastObject)■ Add / remove at either end (e.g. -addObject:, -removeLastObject:)

• Slower operations■ Search (e.g. -containsObject:, -indexOfObject*, -removeObject:)■ Add / remove, arbitrary index (e.g. -insertObject:atIndex:)

Page 140: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSArray / NSMutableArray

•Ordered, indexed, allows duplicates• Fast operations

■ Indexed access (e.g. -objectAtIndex:, -firstObject, -lastObject)■ Add / remove at either end (e.g. -addObject:, -removeLastObject:)

• Slower operations■ Search (e.g. -containsObject:, -indexOfObject*, -removeObject:)■ Add / remove, arbitrary index (e.g. -insertObject:atIndex:)

• Specialty operations■ Binary search (requires a sorted range of an array)

■ -indexOfObject:inSortedRange:options:usingComparator:

Page 141: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSSet / NSMutableSet

Page 142: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSSet / NSMutableSet

•Unordered, no duplicates, hash lookup

Page 143: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSSet / NSMutableSet

•Unordered, no duplicates, hash lookup•Add, remove, and search are fast

■ (e.g. -addObject:, -removeObject:, -containsObject:)

Page 144: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSSet / NSMutableSet

•Unordered, no duplicates, hash lookup•Add, remove, and search are fast

■ (e.g. -addObject:, -removeObject:, -containsObject:)

• Specialty operations■ Set math: test overlap (e.g. -intersectsSet:, -isSubsetOfSet:)■ Set math: modify (e.g. -intersectSet:, -minusSet:, -unionSet:)

Page 145: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSSet / NSMutableSet

•Unordered, no duplicates, hash lookup•Add, remove, and search are fast

■ (e.g. -addObject:, -removeObject:, -containsObject:)

• Specialty operations■ Set math: test overlap (e.g. -intersectsSet:, -isSubsetOfSet:)■ Set math: modify (e.g. -intersectSet:, -minusSet:, -unionSet:)

• Caveats■ Converting array to set loses ordering and duplicates■ Cannot be stored in a property list or JSON

Page 146: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSCountedSet

Page 147: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSCountedSet

•Unordered, no duplicates, hash lookup

Page 148: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSCountedSet

•Unordered, no duplicates, hash lookup• Subclass of NSMutableSet, same operations and caveats

Page 149: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSCountedSet

•Unordered, no duplicates, hash lookup• Subclass of NSMutableSet, same operations and caveats• Tracks net insertion count for each object

■ Incremented on insert, decremented on remove■ -countForObject: returns individual count■ -count still returns number of objects, not sum of insertions

Page 150: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSDictionary / NSMutableDictionary

Page 151: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSDictionary / NSMutableDictionary

•Unordered, key-value entries, unique keys, hash lookup

Page 152: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSDictionary / NSMutableDictionary

•Unordered, key-value entries, unique keys, hash lookup•Add, remove, and search are fast

■ (e.g. -objectForKey:, -setObject:forKey:, -removeObjectForKey:)

Page 153: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSDictionary / NSMutableDictionary

•Unordered, key-value entries, unique keys, hash lookup•Add, remove, and search are fast

■ (e.g. -objectForKey:, -setObject:forKey:, -removeObjectForKey:)

• Specialty operations■ Property list file I/O■ +sharedKeySetForKeys:, +dictionaryWithSharedKeySet: (10.8, iOS 6)

Page 154: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSDictionary / NSMutableDictionary

•Unordered, key-value entries, unique keys, hash lookup•Add, remove, and search are fast

■ (e.g. -objectForKey:, -setObject:forKey:, -removeObjectForKey:)

• Specialty operations■ Property list file I/O■ +sharedKeySetForKeys:, +dictionaryWithSharedKeySet: (10.8, iOS 6)

• Caveats■ Keys must conform to NSCopying (“copy in”)■ NEVER mutate an object that is a dictionary key

Page 155: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSOrderedSet / NSMutableOrderedSet

Page 156: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSOrderedSet / NSMutableOrderedSet

•Ordered, no duplicates, index / hash lookup (10.7, iOS 5)

Page 157: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSOrderedSet / NSMutableOrderedSet

•Ordered, no duplicates, index / hash lookup (10.7, iOS 5)

• Effectively a cross of NSArray and NSSet■ Not a subclass of either one■ Call -array or -set for immutable, live-updating representations

Page 158: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSOrderedSet / NSMutableOrderedSet

•Ordered, no duplicates, index / hash lookup (10.7, iOS 5)

• Effectively a cross of NSArray and NSSet■ Not a subclass of either one■ Call -array or -set for immutable, live-updating representations

• Caveats■ Increased memory usage■ Property list support requires conversions

Page 159: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSIndexSet / NSMutableIndexSet

Page 160: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSIndexSet / NSMutableIndexSet

• Collection of unique NSUInteger values

Page 161: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSIndexSet / NSMutableIndexSet

• Collection of unique NSUInteger values• Reference a subset of objects in NSArray

■ Avoid memory overhead of array copies

Page 162: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSIndexSet / NSMutableIndexSet

• Collection of unique NSUInteger values• Reference a subset of objects in NSArray

■ Avoid memory overhead of array copies

• Efficient storage and coalescing

Page 163: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSIndexSet / NSMutableIndexSet

• Collection of unique NSUInteger values• Reference a subset of objects in NSArray

■ Avoid memory overhead of array copies

• Efficient storage and coalescing• Set arithmetic (intersect, subset, difference)

Page 164: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSIndexSet / NSMutableIndexSet

• Collection of unique NSUInteger values• Reference a subset of objects in NSArray

■ Avoid memory overhead of array copies

• Efficient storage and coalescing• Set arithmetic (intersect, subset, difference)• Caveats

■ Use caution with indexes for mutable arrays

Page 165: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSMapTable / NSHashTable

Page 166: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSMapTable / NSHashTable

• Similar to NSMutableDictionary / NSMutableSet

Page 167: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSMapTable / NSHashTable

• Similar to NSMutableDictionary / NSMutableSet•More flexibility via NSMapTableOptions / NSHashTableOptions

■ May use pointer identity for equality and hashing■ May contain any pointer (not just objects)■ Optional weak references to keys and/or values (zeroing under ARC)■ Optional copy on insert

Page 168: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSMapTable / NSHashTable

• Similar to NSMutableDictionary / NSMutableSet•More flexibility via NSMapTableOptions / NSHashTableOptions

■ May use pointer identity for equality and hashing■ May contain any pointer (not just objects)■ Optional weak references to keys and/or values (zeroing under ARC)■ Optional copy on insert

• Caveats■ Can’t convert non-object contents to dictionary/set■ Beware of premature optimization!

Page 169: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSCache

Page 170: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSCache

• Similar to NSMutableDictionary• Thread-safe•Doesn’t copy keys•Auto-removal under memory pressure• Ideal for objects that can be regenerated on demand

Page 171: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

NSCache

• Similar to NSMutableDictionary• Thread-safe•Doesn’t copy keys•Auto-removal under memory pressure• Ideal for objects that can be regenerated on demand

Building Efficient OS X Apps Nob HillTuesday 4:30PM

Page 172: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Brief Aside: Property Lists

Page 173: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Brief Aside: Property Lists

• Files that store simple hierarchies of data■ XML and binary formats

Page 174: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Brief Aside: Property Lists

• Files that store simple hierarchies of data■ XML and binary formats

• Supports “property list” objects■ NSArray, NSData, NSDate, NSDictionary, NSNumber, NSString■ Others must adopt NSCoding and be archived

Page 175: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Brief Aside: Property Lists

• Files that store simple hierarchies of data■ XML and binary formats

• Supports “property list” objects■ NSArray, NSData, NSDate, NSDictionary, NSNumber, NSString■ Others must adopt NSCoding and be archived

•Mutability is not preserved on read/write

Page 176: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Brief Aside: Property Lists

• Files that store simple hierarchies of data■ XML and binary formats

• Supports “property list” objects■ NSArray, NSData, NSDate, NSDictionary, NSNumber, NSString■ Others must adopt NSCoding and be archived

•Mutability is not preserved on read/write• Inefficient for lots of binary data, large files

Page 177: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Brief Aside: Property Lists

• Files that store simple hierarchies of data■ XML and binary formats

• Supports “property list” objects■ NSArray, NSData, NSDate, NSDictionary, NSNumber, NSString■ Others must adopt NSCoding and be archived

•Mutability is not preserved on read/write• Inefficient for lots of binary data, large files•NSUserDefaults

Page 178: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Brief Aside: Property Lists

• Files that store simple hierarchies of data■ XML and binary formats

• Supports “property list” objects■ NSArray, NSData, NSDate, NSDictionary, NSNumber, NSString■ Others must adopt NSCoding and be archived

•Mutability is not preserved on read/write• Inefficient for lots of binary data, large files•NSUserDefaults•NSPropertyListSerialization

Page 179: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Brief Aside: Property Lists

• Files that store simple hierarchies of data■ XML and binary formats

• Supports “property list” objects■ NSArray, NSData, NSDate, NSDictionary, NSNumber, NSString■ Others must adopt NSCoding and be archived

•Mutability is not preserved on read/write• Inefficient for lots of binary data, large files•NSUserDefaults•NSPropertyListSerialization•NSKeyedArchiver / NSKeyedUnarchiver

Page 180: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Brief Aside: JSON

Page 181: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Brief Aside: JSON

• JavaScript Object Notation (http://json.org)

Page 182: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Brief Aside: JSON

• JavaScript Object Notation (http://json.org)• Lightweight data format

■ Commonly used with web services

Page 183: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Brief Aside: JSON

• JavaScript Object Notation (http://json.org)• Lightweight data format

■ Commonly used with web services

•Works with a few Foundation classes■ NSArray, NSDictionary, NSNull, NSNumber, NSString■ Some restrictions on hierarchy and values

Page 184: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Brief Aside: JSON

• JavaScript Object Notation (http://json.org)• Lightweight data format

■ Commonly used with web services

•Works with a few Foundation classes■ NSArray, NSDictionary, NSNull, NSNumber, NSString■ Some restrictions on hierarchy and values

•NSJSONSerialization (10.7 / iOS 5.0)■ Reading, writing, object validation■ Optional mutability on read■ Fast, built-in, dynamically linked

Page 185: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Real-World Applications

Page 186: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

WWDC App — Refreshing Sessions

Page 187: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

WWDC App — Refreshing Sessions

•Details are stored in Core Data

Page 188: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

WWDC App — Refreshing Sessions

•Details are stored in Core Data• Periodically fetch updates

Page 189: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

WWDC App — Refreshing Sessions

•Details are stored in Core Data• Periodically fetch updates• Performance issues

■ Great speed at first■ More sessions cause lag■ Performance gets bad quickly

Page 190: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

WWDC App — Refreshing Sessions

•Details are stored in Core Data• Periodically fetch updates• Performance issues

■ Great speed at first■ More sessions cause lag■ Performance gets bad quickly

• Profiling reveals non-linear growth

Page 191: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Approach 1WWDC App — Refreshing Sessions

Page 192: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Approach 1WWDC App — Refreshing Sessions

NSArray *sessionsToImport = ...; // Fetched from serverNSManagedObjectContext *context = ...;

for (WWDCSession *session in sessionsToImport) { NSFetchRequest *r = [NSFetchRequest fetchRequestWithEntityName:@"WWDCSession"]; r.predicate = [NSPredicate predicateWithFormat:@"sessionID = %@", session.sessionID]; NSArray *results = [context executeFetchRequest:r error:nil];! WWDCSession *existingSession = [results firstObject]; if (existingSession != nil) { // Merge into existingSession } else { // Insert into context }}

Page 193: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Approach 1WWDC App — Refreshing Sessions

NSArray *sessionsToImport = ...; // Fetched from serverNSManagedObjectContext *context = ...;

for (WWDCSession *session in sessionsToImport) { NSFetchRequest *r = [NSFetchRequest fetchRequestWithEntityName:@"WWDCSession"]; r.predicate = [NSPredicate predicateWithFormat:@"sessionID = %@", session.sessionID]; NSArray *results = [context executeFetchRequest:r error:nil];! WWDCSession *existingSession = [results firstObject]; if (existingSession != nil) { // Merge into existingSession } else { // Insert into context }}

Page 194: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Approach 2WWDC App — Refreshing Sessions

NSArray *sessionsToImport = ...; // Fetched from serverNSManagedObjectContext *context = ...;

NSArray *sessionIDs = [sessionsToImport valueForKey:@"sessionID"];NSFetchRequest *r = [NSFetchRequest fetchRequestWithEntityName:@"WWDCSession"];r.predicate = [NSPredicate predicateWithFormat:@"sessionID in %@", sessionIDs];NSArray *results = [context executeFetchRequest:r error:nil];

for (WWDCSession *session in sessionsToImport) { NSInteger existingSessionIndex = [results indexOfObject:session]; if (existingSessionIndex != NSNotFound) { WWDCSession *existingSession = results[existingSessionIndex]; // Merge into existingSession } else { // Insert into context }}

Page 195: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Approach 2WWDC App — Refreshing Sessions

NSArray *sessionsToImport = ...; // Fetched from serverNSManagedObjectContext *context = ...;

NSArray *sessionIDs = [sessionsToImport valueForKey:@"sessionID"];NSFetchRequest *r = [NSFetchRequest fetchRequestWithEntityName:@"WWDCSession"];r.predicate = [NSPredicate predicateWithFormat:@"sessionID in %@", sessionIDs];NSArray *results = [context executeFetchRequest:r error:nil];

for (WWDCSession *session in sessionsToImport) { NSInteger existingSessionIndex = [results indexOfObject:session]; if (existingSessionIndex != NSNotFound) { WWDCSession *existingSession = results[existingSessionIndex]; // Merge into existingSession } else { // Insert into context }}

Page 196: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Approach 2WWDC App — Refreshing Sessions

NSArray *sessionsToImport = ...; // Fetched from serverNSManagedObjectContext *context = ...;

NSArray *sessionIDs = [sessionsToImport valueForKey:@"sessionID"];NSFetchRequest *r = [NSFetchRequest fetchRequestWithEntityName:@"WWDCSession"];r.predicate = [NSPredicate predicateWithFormat:@"sessionID in %@", sessionIDs];NSArray *results = [context executeFetchRequest:r error:nil];

for (WWDCSession *session in sessionsToImport) { NSInteger existingSessionIndex = [results indexOfObject:session]; if (existingSessionIndex != NSNotFound) { WWDCSession *existingSession = results[existingSessionIndex]; // Merge into existingSession } else { // Insert into context }}

Page 197: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Approach 3WWDC App — Refreshing Sessions

NSArray *sessionsToImport = ...; // Fetched from serverNSManagedObjectContext *context = ...;

NSArray *sessionIDs = [sessionsToImport valueForKey:@"sessionID"];NSFetchRequest *r = [NSFetchRequest fetchRequestWithEntityName:@"WWDCSession"];r.predicate = [NSPredicate predicateWithFormat:@"sessionID in %@", sessionIDs];NSArray *results = [context executeFetchRequest:r error:nil];NSDictionary *sessionsKeyedByID = [NSDictionary dictionaryWithObjects:results forKeys: [results valueForKey:@"sessionID"]];

for (WWDCSession *session in sessionsToImport) { WWDCSession *existingSession = sessionsKeyedByID[session.sessionID]; if (existingSession != nil) { // Merge into existingSession } else { // Insert into context }}

Page 198: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Approach 3WWDC App — Refreshing Sessions

NSArray *sessionsToImport = ...; // Fetched from serverNSManagedObjectContext *context = ...;

NSArray *sessionIDs = [sessionsToImport valueForKey:@"sessionID"];NSFetchRequest *r = [NSFetchRequest fetchRequestWithEntityName:@"WWDCSession"];r.predicate = [NSPredicate predicateWithFormat:@"sessionID in %@", sessionIDs];NSArray *results = [context executeFetchRequest:r error:nil];NSDictionary *sessionsKeyedByID = [NSDictionary dictionaryWithObjects:results forKeys: [results valueForKey:@"sessionID"]];

for (WWDCSession *session in sessionsToImport) { WWDCSession *existingSession = sessionsKeyedByID[session.sessionID]; if (existingSession != nil) { // Merge into existingSession } else { // Insert into context }}

Page 199: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Approach 3WWDC App — Refreshing Sessions

NSArray *sessionsToImport = ...; // Fetched from serverNSManagedObjectContext *context = ...;

NSArray *sessionIDs = [sessionsToImport valueForKey:@"sessionID"];NSFetchRequest *r = [NSFetchRequest fetchRequestWithEntityName:@"WWDCSession"];r.predicate = [NSPredicate predicateWithFormat:@"sessionID in %@", sessionIDs];NSArray *results = [context executeFetchRequest:r error:nil];NSDictionary *sessionsKeyedByID = [NSDictionary dictionaryWithObjects:results forKeys: [results valueForKey:@"sessionID"]];

for (WWDCSession *session in sessionsToImport) { WWDCSession *existingSession = sessionsKeyedByID[session.sessionID]; if (existingSession != nil) { // Merge into existingSession } else { // Insert into context }}

Page 200: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Eliminating Extra Work

Page 201: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Eliminating Extra Work

•Minimize redundancy, especially “expensive” code■ Particularly within loops

Page 202: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Eliminating Extra Work

•Minimize redundancy, especially “expensive” code■ Particularly within loops

• Take advantage of faster lookup when possible■ Dictionaries and sets

Page 203: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Eliminating Extra Work

•Minimize redundancy, especially “expensive” code■ Particularly within loops

• Take advantage of faster lookup when possible■ Dictionaries and sets

•Use mutable collections (and strings) when it makes sense

Page 204: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Eliminating Extra Work

•Minimize redundancy, especially “expensive” code■ Particularly within loops

• Take advantage of faster lookup when possible■ Dictionaries and sets

•Use mutable collections (and strings) when it makes sense• Streamline how you access your data

Page 205: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Eliminating Extra Work

•Minimize redundancy, especially “expensive” code■ Particularly within loops

• Take advantage of faster lookup when possible■ Dictionaries and sets

•Use mutable collections (and strings) when it makes sense• Streamline how you access your data•Don’t reinvent the wheel

■ e.g. -[NSArray componentsJoinedByString:]

Page 206: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

ExampleEliminating Extra Work

Page 207: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

ExampleEliminating Extra Work

- (NSArray*) doSomethingWithArray:(NSArray*)array{ NSArray *newArray = [NSArray array]; for (id object in array) { id newObject = [self doSomethingWithObject:object]; if (newObject != nil) { newArray = [newArray arrayByAddingObject:newObject]; } } return newArray;}

Page 208: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

ExampleEliminating Extra Work

- (NSArray*) doSomethingWithArray:(NSArray*)array{ NSArray *newArray = [NSArray array]; for (id object in array) { id newObject = [self doSomethingWithObject:object]; if (newObject != nil) { newArray = [newArray arrayByAddingObject:newObject]; } } return newArray;}

Page 209: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

ExampleEliminating Extra Work

- (NSArray*) doSomethingWithArray:(NSArray*)array{ NSMutableArray *newArray = [NSMutableArray array]; for (id object in array) { id newObject = [self doSomethingWithObject:object]; if (newObject != nil) { [newArray addObject:newObject]; } } return [newArray copy]; // Copy is immutable}

• Similarly, appending to an NSMutableString

Page 210: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

ExampleEliminating Extra Work

- (NSArray*) doSomethingWithArray:(NSArray*)array{ NSMutableArray *newArray = [NSMutableArray array]; for (id object in array) { id newObject = [self doSomethingWithObject:object]; if (newObject != nil) { [newArray addObject:newObject]; } } return [newArray copy]; // Copy is immutable}

• Similarly, appending to an NSMutableString

Page 211: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Don’t leave performance on the table

Page 212: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

More Information

Dave DeLongApp Frameworks and Developer Tools Evangelist [email protected]

Apple Developer Forumshttp://devforums.apple.com

Collections Programming Topicshttp://developer.apple.com/documentation/Cocoa/Conceptual/Collections/

Property List Programming Guidehttp://developer.apple.com/documentation/Cocoa/Conceptual/PropertyLists/

Archives and Serializations Programming Guidehttp://developer.apple.com/documentation/Cocoa/Conceptual/Archiving/

Page 213: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Related Sessions

Building Efficient OS X Apps Nob HillTuesday 4:30PM

Hidden Gems in Cocoa and Cocoa Touch Nob HillFriday 10:15AM

Page 214: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Summary

Page 215: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Summary

• Complexity kills large-scale performance

Page 216: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Summary

• Complexity kills large-scale performance• Know how much work your code does

Page 217: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Summary

• Complexity kills large-scale performance• Know how much work your code does•Avoid redundancy, strive for efficiency

Page 218: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Summary

• Complexity kills large-scale performance• Know how much work your code does•Avoid redundancy, strive for efficiency• Focus on biggest performance wins

■ Profile and analyze, don’t assume

Page 219: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Summary

• Complexity kills large-scale performance• Know how much work your code does•Avoid redundancy, strive for efficiency• Focus on biggest performance wins

■ Profile and analyze, don’t assume

• Prefer built-in collections and API

Page 220: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Summary

• Complexity kills large-scale performance• Know how much work your code does•Avoid redundancy, strive for efficiency• Focus on biggest performance wins

■ Profile and analyze, don’t assume

• Prefer built-in collections and API•Design according to your needs

Page 221: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Summary

• Complexity kills large-scale performance• Know how much work your code does•Avoid redundancy, strive for efficiency• Focus on biggest performance wins

■ Profile and analyze, don’t assume

• Prefer built-in collections and API•Design according to your needs• Think about performance early

Page 222: Designing Code for Performance - Apple Inc.€¦ · Complexity and “Big O” Notation •Rank algorithms by efficiency (time, memory, etc.) The letter “O” represents the order

Recommended