soft-shake.ch - Optimizing iOS applications

Preview:

DESCRIPTION

Marc-Antoine Scheurer Tips and tricks to get the best performance out of an iOS application.

Citation preview

Marc-Antoine Scheurer

2010

i5

Optimizing iOS applications

Agilité iPhone Java Incubateur

8:15 Accueil des participantsAccueil des participantsAccueil des participantsAccueil des participants

8:40 Mot des organisateurs & Criée des orateursMot des organisateurs & Criée des orateursMot des organisateurs & Criée des orateursMot des organisateurs & Criée des orateurs

9:00 Keynote de Nicolas Martignole (30 minutes)Keynote de Nicolas Martignole (30 minutes)Keynote de Nicolas Martignole (30 minutes)Keynote de Nicolas Martignole (30 minutes)

9:40

10:40

- A1 -Le terrain Agile

Jean-Philippe Vigniel

- I1-Hello iPhone

Stephane Tavera

- J1 -NOSQL also means RDF stores: an

Android case studyFabrizio Giudci

- X1 -Le développement durable

Dominic Williams

11:00

12:00

- A2 -Integration of User Centered Design

in Agile Development of RIAJ. Borkenhagen, J. Desmazières

- I2 -Développement d'une application

iPhone pilotée par les testsEmmanuel Etasse, Van-Charles Tran

- J2 -La Tequila du développement Web

Nicolas Martignole

- X2 -Cloud Computing: anatomie et

pratiqueMarc-Elian Bégin

12:20

13:20

- A3 -Adoption de l'Agilité par les usages

Xavier Warzee

- I3 -Distribution d'applications iPhone

en Entreprise: Réalisation d'un AppStore interne

Géraud de Laval

- J3 -Vaadin - Rich Web Applications in

Server-side Java without Plug-ins or JavaScript

Joonas Lehtinen

- X3 -Les DVCS sont vos amis

Sébastien Douche

Pause repas (50 minutes)Pause repas (50 minutes)Pause repas (50 minutes)Pause repas (50 minutes)

14h10 Keynote de Regis Medina (30 minutes)Keynote de Regis Medina (30 minutes)Keynote de Regis Medina (30 minutes)Keynote de Regis Medina (30 minutes)

14h50

15h50

- A4 - Scrum, introduction et mise en

oeuvre avec iceScrumClaude Aubry

- I4 -Agile iOS Development

Jérôme Layat, Alexander Osterwalder

- J4 -JAX-RS and Java EE 6

Paul Sandoz

- X4 -IT Design & Ergonomy

Pascal Petit, Aude Lussigny

16h10

17h10

- A5 -Agilité : 10 ans déjà

Thierry Cros

- I5 -Optimizing iOS applications

Marc-Antoine Scheurer

- J5 -Ecrivez et automatisez vos tests

fonctionnels avec jBehaveXavier Bourguignon

- X5 -NoSQL : Enfin de la biodiversité

dans l'écosystème des BDOlivier Mallassi

17h30

18h30

- A6 -Lean engineering

Jean-Christophe Dubail

- I6 -iPhone et Agile, l'amour vache

Guillaume Duquesnay

- J6 -Let's make this test suite run faster

David Gageot

- X6 -The feel of Scala

Mario Fusco

Mot de la fin & tombolaMot de la fin & tombolaMot de la fin & tombolaMot de la fin & tombola

Programme de la Conférence

www.soft-shake.ch

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Optimizing iOS Applications

Marc-Antoine Scheurermarco@sente.ch

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Optimizing is...

• Risky: “If it ain’t broke, don’t fix it”

• A hardware problem: “Buy a faster computer”

• Time consuming: “I don’t have time for performance work”

• Complicated: “I don’t know where to start or what to do”

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Why?

• For the user: better experience

• For you: beat the competition

• For the OS: watch out the watchdog

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

A Hardware Problem:Limited Resources

3G 3GS 4 iPadCPU ARM 11 ARM Cortex A8 A4 (Cortex A8) A4 (Cortex A8)clock 412 MHz 600 MHz 1 GHz 1GHz

L1 32 KB 64 KB 64 KB 64 KBL2 - 256 KB 640 KB 640 KB

GPUtriangles /

s

PowerVR MBX Lite0.6 M

PowerVR SGX5.2 M

A4 (PowerVR SGX)28 M ??

A4 (PowerVR SGX)28 M ??

RAM 128 MB 256 MB 512 MB 256 MBavailable 40 MB 150 MB 400 MB ? 150 MB

Flashavailable

8 - 32 GB2 GB

16 - 32 GB2 GB

16 - 32 GB2 GB

16 - 32 - 64 GB2 GB

Screen 480x320 480x320 960x640 1024x728More GPS Compass Gyroscope

Battery 6h on WiFi 9h on WiFi 10h on WiFi 10-12h video

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Where to start?Measuring Performance

• Guessing often does not work

• Measure - Change - Measure

• Use measuring tools

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Measuring Tools

• NSLog

• Instruments

• Simulator

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

NSLog

NSDate *startTime = [NSDate date];... NSLog (@"Elapsed time: %.3f", -[startTime timeIntervalSinceNow]);

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

InstrumentsTool Introduced

Objective C 1988

Interface Builder 1988*

Xcode 1988†

Instruments 2007‡

† Project Builder, renamed Xcode in 2003‡ Shikari, Shark in 2002

* SOS Interface, 1984-1986 (LISP, Mac)

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Instruments• Profiling tool

• CPU

• Memory

• CoreAnimation

• CoreData

• OpenGL

• Power

• etc.

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Simulator

• Software simulator ≠ hardware emulator

Simulator 3G

i386 ARM

2.5 GHz 400 MHz

Unlimited memory 40 MB

• Measure and test on oldest supported device (3G)

• Simulator OK to check memory usage

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Better user experience

1. Responsive application

2. No crash (or kill by the watchdog)

3. Save battery life

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

1. Responsive applications

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Time

• Faster code

• makes applications more responsive

• uses less power

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Time

• Animation

• Objective C

• C and ARM code generation

• Frameworks

• File system

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Animation

• Demo

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Animation

• Scrolling at 60 fps

• Reuse identifier

• Opaque views

• Reuse formatters

• UINib (4.x)

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Objective C

• Blocks

• IMP caching

[array indexesOfObjectsWithOptions:NSEnumerationConcurrent passingTest:^(id obj, NSUInteger idx, BOOL *stop) { return [obj test:value]; } ]

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

• Demo

Objective C

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

C and ARM Code Generation

• Demo

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

C and ARM Code Generation

• ARM v6 (2G, 3G)

• ARM v7 (3GS, 4)

• -Os vs -O3

• Floating points: remove Thumb on v6

• Contiguous memory, shadow variables, etc.

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Frameworks

• Foundation

• Accelerate

• Grand Central Dispatch

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Foundation

• NSMutableArray, NSMutableString

• insert O(N), O(1) at begin and end

• NSMutableDictionary, NSMutableSet

• lookup O(1) with good hash function

• NSMutableIndexSet

• Store integers without NSNumber

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Accelerate• ARM v6• Integer unit with 16 registers

• Hardware floating-point (VFP)

• 32 single precision registers

• 16 double precision registers

• ARM v7• Integer unit with 16 registers

• Legacy VFP support

• NEON: 16 128-bit vector registers

• Single precision floating-point uses NEON

• NEON can decode MP3 on 10MHz CPU

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Accelerate

• Makes using VFP and NEON easy

• Demo

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Accelerate

• 2000 APIs for hardware accelerated math

• vDSP (Digital Signal Processing)

• Fourier transforms

• BLAS (Basic Linear Algebra Subprograms)

• Matrix product

• LAPACK (Linear algebra)

• Solving system of linear equations

• Later? vImage, vForce, ...

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Grand Central Dispatch

• Concurrent programming

• Multicore or single core

• Easier and lighter than threads

• Use to move long processes off the main thread

• dispatch_async()

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

• Demo

Grand Central Dispatch

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

File system

• Access to Flash memory is relatively slow

• Speed vary a lot from device to device

• For large files use memory mapped files+[NSData dataWithContentsOfMappedFile:]

• Long I/O off the main thread

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

File System• I/O of small amount of data:

• NSUserDefaults

• Property Lists

• NSArchiver

• I/O of large amount of data:

• Incremental formats

• Databases (CoreData)

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Property Lists• Binary Format 2-3x faster than XML

• Use NSPropertyListSerialization

-[NSArray writeToFile:atomically:] -[NSDictionary writeToFile:atomically:] -[NSString writeToFile:atomically:encoding:error:]

NSData *data = [NSPropertyListSerialization dataWithPropertyList:dictionary format:NSPropertyListBinaryFormat_v1_0 options:0 error:NULL]; [data writeToFile:path atomically:YES];

• Slow:

• Fast:

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

NSArchiver

• Not an incremental file format

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Database

• Use CoreData

• Do not import large quantity of data...

• Add object stores instead

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Database Search

• Unicode string comparisons are expensive

• Use normalized derived attribute (without accents)

• Use <= and < instead of BEGINSWITH

• Prefer prefix searching

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Database Search• Point de Vue app: 25’000 records

3G Before After

[[each name] rangeOfString:searchString options:(NSAnchored| NSCaseInsensitive| NSDiacriticInsensitiveSearch)].location != NSNotFound

[[each asciiName] hasPrefix:searchString ]

“l” 0.704 0.450

“la” 0.032 0.024

“lau” 0.010 0.008

“laus” 0.001 0.001

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

2. No Crash

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Activity Watchdog

Maximum Allowed TimeMaximum Allowed Time

Launch 20 s

Resume 10 s

Suspend 10 s

Quit 6 s

Operation 10 min

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Memory Watchdog“Jetsam”

• Watches memory pressure

• Issues low memory warning

• Instant termination of application

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Memory

• No swap

• (but yes: virtual memory)

• Memory usage also impacts time

• allocation time,

• unloading of executable code, ...

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Memory Usage

• Avoid

• spikes

• leaks

• abandoned memory

• zombies

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Memory Spikes

• Be smart with autorelease

• Process large quantities of data in batches

• Nested autorelease pools

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

• Demo

Memory Spikes

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Memory Leaks

• Allocated memory that is inaccessible

• Unbalanced retain/release

• Forget to release property’s original value

• Leaks Instrument examines heap for leaked memory, identify allocation

• Xcode: Build and Analyze

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Abandoned Memory

• Wasted memory

• Accessible but never used

• Memory should not grow without bounds

• Detect with Allocation Instrument: “heap shots”

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Zombies

• Messages send to deallocated object

• Detect with Zombies template

• or Allocations “Enable zombie detection”

• Simulator only

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

3. Energy

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Energy (iPhone 3G)

• 3G, WiFi, Bluetooth, GPS: 2 W

• CPU + GPU: 800 mW

• Screen: 200 mW

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Radios and sensors

• Network

• CoreLocation

• CoreMotion

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Network

• Bandwidth usage impacts time and power

• Use compact protocols (JSON vs XML)

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

3G

• 3G networks require phones stay in high-power state for a few seconds after last packet is sent or received

• Limit number of connections

• Do not poll

• Use compact data formats

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

WiFi & 2G

• Less power than 3G

• 3G > 2G > WiFi

• Allowed to idle immediately

• 2G much slower

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

CPU• Burst

• Do not poll, use events

• Accelerate: more power, less energy

Power

Time

with NEONwithout NEON

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

CoreLocation

• Use minimum required accuracy

GPS kCLLocationAccuracyBest

GPS kCLLocationAccuracyNearestTenMeters

WiFi kCLLocationAccuracyHundredMeters

Cell / WiFi kCLLocationAccuracyKilometer

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

CoreLocation

• distanceFilter

• how often you receive location changed notifications

• default: all changes, many events, high CPU usage

• stopUpdatingLocation

• when good enough accuracy, switch GPS off.

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

CoreMotion

• Same thing

• Turn sensors off when in background (4.x)

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Energy diagnostics

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Energy usage

• Works on

• 3GS

• 4

• iPod 2 & 3

Level Battery life

20 Less than 1 hour

10 About 10 hours

1 More than 20 hours

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Measure on the go• Enable device

to collect data

• Import in Instruments

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Summary

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Instruments’ instrumentsCPU

Memory

File System

Core Data

Graphics

Energy

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Instruments Wireless• Connect device with USB

• Hold alt while choosing target

• Choose wireless device

• Disconnect from USB

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

When?

• All the time

© Copyright 2010, Sente SA. All rights reserved. http://www.sente.ch

Useful links

• Xcode Developer documentation

• Applehttp://developer.apple.com/iphone

http://developer.apple.com/videos/wwdc/2010/

• Developer forumshttp://www.iphonedevsdk.com/

http://stackoverflow.com

• Developer classesStanford iPhone Application Development (english, free) sur iTunesU http://deimos3.apple.com/WebObjects/Core.woa/Browse/itunes.stanford.edu.3124430053.03124430055

Sen:te (french, paying)http://www.iphone-class.com

Recommended