Advanced Memory Analysis with Instruments. Daniel Delwood Performance Tools Engineer

Similar documents
Mastering Xcode for iphone OS Development Part 2. Marc Verstaen Sr. Manager, iphone Tools

Announcement. Final Project Proposal Presentations and Updates

Advanced Debugging and the Address Sanitizer

Mastering Xcode for iphone OS Development Part 1. Todd Fernandez Sr. Manager, IDEs

CS193P - Lecture 3. iphone Application Development. Custom Classes Object Lifecycle Autorelease Properties

CS193P - Lecture 10. iphone Application Development. Performance

Kevin van Vechten Core OS

Design Phase. Create a class Person. Determine the superclass. NSObject (in this case)

Collections & Memory Management. Lecture 2

IPHONE DEVELOPMENT. Getting Started with the iphone SDK

Building Watch Apps #WWDC15. Featured. Session 108. Neil Desai watchos Engineer

CS193E Lecture #3 Categories and Protocols Cocoa Memory Management

Thread Sanitizer and Static Analysis

Profiling in Depth. Do you know where your code is? Session 412. Kris Markel Performance Tools Engineer Chad Woolf Performance Tools Engineer

What s New in the LLVM Compiler. Chris Lattner LLVM Chief Architect

iphone App Basics iphone and ipod touch Development Fall 2009 Lecture 5

Monetize and Promote Your App with iad

ITP 342 Advanced Mobile App Dev. Memory

Intro to Native ios Development. Dave Koziol Arbormoon Software, Inc.

ITP 342 Mobile App Development. Singleton

ios Memory Deep Dive #WWDC18 Kyle Howarth, Software Engineer James Snee, Software Engineer Kris Markel, Software Engineer

Introducing the Modern WebKit API

ITP 342 Mobile App Development. Data Persistence

A little more Core Data

Finding Bugs Using Xcode Runtime Tools

Accessibility on ios. Developing for everyone. Frameworks #WWDC14. Session 210 Clare Kasemset ios Accessibility

Stanford CS193p. Developing Applications for iphone 4, ipod Touch, & ipad Spring Stanford CS193p Spring 2011

ios Application Development Course Details

Introducing On Demand Resources

Power, Performance, and Diagnostics

CS 47. Beginning iphone Application Development

Objective-C Primer. iphone Programmer s Association. Lorenzo Swank September 10, 2008

Mobile Application Programming. Memory Management

Adapting to the New UI of OS X Yosemite

The MVC Design Pattern

epicurious Anatomy of an ios app Robert Tolar Haining June 25, 2010 ConvergeSE

WatchKit In-Depth, Part 2

Accessibility on OS X

Announcements. Today s Topics

Working Effectively with Objective-C on iphone OS. Blaine Garst Wizard of Runtimes

OVERVIEW. Why learn ios programming? Share first-hand experience. Identify platform differences. Identify similarities with.net

Adopting Advanced Features of the New UI

Creating Great App Previews

COCOA WORKSHOP PART 1. Andreas Monitzer

Designing for Apple Watch

Address Book for iphone

CS193p Spring 2010 Wednesday, March 31, 2010

Data Management

What s New in tvos #WWDC16. App Frameworks. Session 206. Hans Kim tvos Engineer

Implementing UI Designs in Interface Builder

Localizing with Xcode 6

Introducing CloudKit. A how-to guide for icloud for your Apps. Frameworks #WWDC14. Session 208 Olivier Bonnet CloudKit Client Software

What's New in UIKit Dynamics and Visual Effects Session 229

Create an App that will drop PushPins onto a map based on addresses that the user inputs.

What s New in Notifications

Creating Extensions for ios and OS X, Part Two

Creating Complications with ClockKit Session 209

ITP 342 Mobile App Development. Data Persistence

Introducing the Photos Frameworks

Stanford CS193p. Developing Applications for iphone 4, ipod Touch, & ipad Fall Stanford CS193p Fall 2010

Contents. iphone Training. Industry Trainers. Classroom Training Online Training ON-DEMAND Training. Read what you need

Seamless Linking to Your App

Review. iphone Application Programming Lecture 2: Objective-C, Cocoa. History. Objective-C. Device restrictions. Interaction paradigm changes

Mobile Application Development

Advanced Performance Optimization on iphone OS

Building a (Core) Foundation. Rob Napier

ios: Objective-C Primer

Data Management: Event Handling

Data IAP 2010 iphonedev.csail.mit.edu edward benson / Thursday, January 14, 2010

Objective-C and COCOA Applications

View Controller Advancements for ios8

What s New in Xcode App Signing

Cocoa Programming. David Chisnall. March 18,

Objective-C Runtime. Cocoa s Jewel in the Crown. NSConference Nicolas

Using and Extending the Xcode Source Editor

Science. Computer Science

AVAudioPlayer. avtouch Application

Creating Content with iad JS

Storyboards and Controllers on OS X

What s New in Core Location

Writing Energy Efficient Code

Review. iphone Application Programming Lecture 2: Objective-C, Cocoa. History. Objective-C. Device restrictions. Interaction paradigm changes

Improving your Existing Apps with Swift

Memory Management: The Details

What s New in Core Data?

Memory Management: The process by which memory is shared, allocated, and released. Not applicable to cache memory.

Assignment II: Foundation Calculator

What s New in CloudKit

Editing Media with AV Foundation

Examples and solutions for iphone & ipad. J. Harrington B. Trebitowski C. Allen S. Appelcline MANNING

Designing Great Apple Watch Experiences

Xcode 6 and ios 8 What s New for Software Developers

Slide 6-1. Processes. Operating Systems: A Modern Perspective, Chapter 6. Copyright 2004 Pearson Education, Inc.

Page 1. GUI Programming. Lecture 13: iphone Basics. iphone. iphone

Game Center Techniques, Part 1

Mastering UIKit on tvos

Fix Bugs Faster Using Activity Tracing

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

Stanford CS193p. Developing Applications for ios. Fall Stanford CS193p. Fall 2011

New UIKit Support for International User Interfaces

Transcription:

Advanced Memory Analysis with Instruments Daniel Delwood Performance Tools Engineer 2

Memory Analysis What s the issue? Memory is critical to performance Limited resource Especially on iphone OS 3

4

Memory Analysis When to use Instruments Understand your app s memory usage Reduce wasted memory Diagnose memory related crashes Be proactive about usage Avoid termination Better multitasking citizen 5

Memory Analysis Eliminating Leaks Messages to Deallocated Objects Using Autorelease Properly Abandoned Memory Responding to Memory Warnings 6

Eliminating Leaks What constitutes a leak? Allocated memory that can no longer be reached No more pointers to it MyObject NSString *name; NSString 1 - (id)init { if (self = [super init]) { name = [[NSString alloc] initwithformat:...]; } return self; } 7

Eliminating Leaks What constitutes a leak? Allocated memory that can no longer be reached No more pointers to it MyObject NSString *name; NSString - (void)dealloc { [super dealloc]; } 1 missing: [name release]; 8

Eliminating Leaks How do you find them? 9

Eliminating Leaks Leaks instrument Identifies leaked memory Conservative memory analysis Misses some, but reliable Stacks Heap Objects Leaks Global Data 10

Eliminating Leaks Found the leaked object! Now what? 11

Eliminating Leaks Allocations instrument Tracks all malloc heap allocations C, Objective-C, C++ Malloc/Free/Retain/Release/Autorelease Type statistics Call Trees Incurs overhead 12

Finding/Fixing Leaks Demo Daniel Delwood Performance Tools Engineer 13

Eliminating Leaks Can t just look at the allocation point! Allocation backtrace isn t the whole story Framework-created objects can be leaked by app code Focus on a single instance to investigate Leaked Object # Address NSCFString 95 < multiple > NSCFString NSCFString NSCFString 0x6e63390 0x6e620f0 0x6e61fc0 14

Memory Management Programming Guide for Cocoa http://developer.apple.com/iphone/library/documentation/cocoa/conceptual/memorymgmt/ 15

Memory Analysis Eliminating Leaks Messages to Deallocated Objects Using Autorelease Properly Abandoned Memory Responding to Memory Warnings 16

Abandoned Memory What is it? Leaked memory Allocated memory that can no longer be reached Inaccessible no more pointers to it Abandoned Memory Accessible allocated memory that is never used again Wasted or forgotten memory Occurs also when garbage collected 17

Abandoned Memory Examples Extraneous information - (void)updateboardwithmove:(tictactoemove*)move {! [_previousgamestates addobject:[self currentgamestate]];!... } - (void)newgame:(id)sender {! [_previousgamestates addobject:[tictactoestate blankstate]];!... } - (void)undoorredo:(id)sender {! TicTacToeState *laststate = [self currentgamestate];! [self setgamestate:[_previousgamestates lastobject]];! [_previousgamestates addobject:currentstate]; } 18

Abandoned Memory Examples Extraneous information NSMutableArray *_previousgamestates; Useless state (abandoned) Useful undo state 19

Abandoned Memory Examples Faulty cache - (NSImage*)_imageInDirectory:(NSURL*)url index:(nsuinteger)index {! NSImage *image = [_imagecache objectforkey:[nsstring stringwithformat:@"%@, %lu", url, index]];! if (!image) {!! NSURL *imageurl = [[[NSFileManager defaultmanager] contentsofdirectoryaturl:url...!! image = [[[NSImage alloc] initwithcontentsofurl:imageurl] autorelease];!! [_imagecache setobject:image forkey:[nsstring stringwithformat:@"%d, %lu", url, index]];! }! return image; } 20

Abandoned Memory Examples Faulty cache - (NSImage*)_imageInDirectory:(NSURL*)url index:(nsuinteger)index {! NSImage *image = [_imagecache objectforkey:[nsstring stringwithformat:@"%@, %lu", url, index]];! if (!image) {!! NSURL *imageurl = [[[NSFileManager defaultmanager] contentsofdirectoryaturl:url...!! image = [[[NSImage alloc] initwithcontentsofurl:imageurl] autorelease];!! [_imagecache setobject:image forkey:[nsstring stringwithformat:@"%d, %lu", url, index]];! }! return image; } 21

Abandoned Memory Examples Faulty cache - (NSImage*)_imageInDirectory:(NSURL*)url index:(nsuinteger)index {! NSImage *image = [_imagecache objectforkey:[nsstring stringwithformat:@"%@, %lu", url, index]];! if (!image) {!! NSURL *imageurl = [[[NSFileManager defaultmanager] contentsofdirectoryaturl:url...!! image = [[[NSImage alloc] initwithcontentsofurl:imageurl] autorelease];!! [_imagecache setobject:image forkey:[nsstring stringwithformat:@"%d, %lu", url, index]];! }! return image; } @ file://localhost/library/desktop%20pictures/abstract/, 2 @ 1484592, 2 22

Abandoned Memory How to detect it Basic principle Memory should not grow without bound when repeating an operation that returns the user to the same state For example: Pushing and popping a view controller Opening and closing a window Changing app preferences back and forth 23

Abandoned Memory How to detect it 1. Get your application into a starting state 2. Perform an action and return to that state 3. Take a snapshot of the heap Repeat! 24

Abandoned Memory Demo Daniel Delwood Performance Tools Engineer 25

Abandoned Memory Heapshot details Baseline Time 26

Abandoned Memory Heapshot details Baseline #1 4 Time 27

Abandoned Memory Heapshot details Baseline #1 #2 4 2 Time 28

Abandoned Memory Heapshot details Baseline #1 #2 #3 4 02 20 Time 29

Memory Analysis Eliminating Leaks Messages to Deallocated Objects Using Autorelease Properly Abandoned Memory Responding to Memory Warnings Victor Hernandez Performance Tools Engineer 30

31

Exception Type: EXC_BAD_ACCESS (SIGBUS) Exception Codes: KERN_PROTECTION_FAILURE at 0x00000010 Crashed Thread: 0 Thread 0 Crashed: 0 libobjc.a.dylib 0x0000286c objc_msgsend + 16 1 Foundation 0x0001219c -[NSString stringbyappendingformat:] + 84 2 Reader 0x000031d4 -[RootViewController tableview:cellforrowatindexpath:] + 32 3 UIKit 0x0007e18c -[UITableView _createpreparedcellforglobalrow:withindexpath:] + 492 4 UIKit 0x0007ded8 -[UITableView(UITableViewInternal) _createpreparedcellforglobalrow:] + 28 5 UIKit 0x000530e2 -[UITableView(_UITableViewPrivate) _updatevisiblecellsnow:] + 930 6 UIKit 0x000514da -[UITableView layoutsubviews] + 134 7 UIKit 0x0000f874 -[UIView(CALayerDelegate) _layoutsublayersoflayer:] + 20 8 CoreFoundation 0x000277f8 -[NSObject(NSObject) performselector:withobject:] + 16 32

Messages to Deallocated Objects Over-released objects [[NSString alloc] initwithformat:...]; Crash NSString 01 [string release]; [string stringbyappendingformat:...]; 33

Messages to Deallocated Objects NSObject NSZombie [[NSString alloc] initwithformat:...]; NSZombie NSString 01 [string release]; [string stringbyappendingformat:...]; 34

Messages to Deallocated Objects Detect them with Zombies template 35

Zombies Demo Victor Hernandez Performance Tools Engineer 36

A received object is normally guaranteed to remain valid within the method it was received in (exceptions include multithreaded applications and some Distributed Objects situations, although you must also take care if you modify an object from which you received another object). Memory Management Programming Guide for Cocoa http://developer.apple.com/iphone/library/documentation/cocoa/conceptual/memorymgmt/ 37

Messages to Deallocated Objects Zombies template Causes memory growth use iphone/ipad Simulator Not suitable to be used with Leaks Last objc message is not always to blame 38

Memory Analysis Eliminating Leaks Messages to Deallocated Objects Using Autorelease Properly Abandoned Memory Responding to Memory Warnings 39

Responding to Memory Warnings A fact of life on iphoneos When system needs memory, notifications go out Multitasking increases memory demands Respond or be terminated - (void)didreceivememorywarning {... } - (void)applicationdidreceivememorywarning: (UIApplication *)app {... } 40

Responding to Memory Warnings Deciding what memory to free Based on resident, dirty pages Instruments helps you identify that memory 0xf00000 read 0xfb0000 Mapped memory tokyo.tiff protection: rw- 41

Responding to Memory Warnings Deciding what memory to free Based on resident, dirty pages Instruments helps you identify that memory 0xf00000 read 0xfb0000 Resident memory protection: rwtokyo.tiff 42

Responding to Memory Warnings Deciding what memory to free Based on resident, dirty pages Instruments helps you identify that memory 0xf00000 write dirty page 0xfb0000 Resident memory protection: rwtokyo.tiff 43

Responding to Memory Warnings Watching your Virtual Memory 44

Responding to Memory Warnings VM Tracker instrument Takes snapshots of virtual memory Similar to vmmap More granular than Activity Monitor instrument For each region and each page: Categorizes by type Identifies protection Reports resident, dirty state 45

Responding to Memory Warnings Checking your efforts Proactively check your work Use simulator to manually trigger a memory warning Use VM Tracker to see your app respond 46

VM Tracker Demo Victor Hernandez Performance Tools Engineer 47

Memory Analysis Eliminating Leaks Messages to Deallocated Objects Using Autorelease Properly Abandoned Memory Responding to Memory Warnings Daniel Delwood Performance Tools Engineer 48

Using Autorelease Properly Memory high-water mark matters Use Allocations and VM Tracker graphs to identify spikes 10.6 MB 2.4 MB 49

Using Autorelease Properly Memory high-water mark matters Use Allocations and VM Tracker graphs to identify spikes Be careful of autoreleased allocations in loops could return a new autoreleased object every time for (i = 0; i < database.lastemployee.number; i++) {! Person *employee = [database employeewithnumber:i];! if ([[tableview selectedrowindexes] containsindex:employee.groupid]) {!! [[grouplistsbyid objectforkey:[nsnumber numberwithint:groupid]] addobject:employee];! } } returns an autoreleased immutable copy returns autoreleased NSNumber 50

Using Autorelease Properly Memory high-water mark matters Use Allocations and VM Tracker graphs to identify spikes Be careful of autoreleased allocations in loops No magic! autorelease is just a delayed release -[NSAutoreleasePool drain] 51

Summary Memory is a limited resource Instruments helps you avoid wasting/mis-using memory Be proactive and profile your app 52

More Information Michael Jurewitz Developer Tools Evangelist jurewitz@apple.com Instruments Documentation Instruments User Guide Xcode documentation Apple Developer Forums http://devforums.apple.com 53

Related Sessions What s New in Instruments Advanced Performance Analysis with Instruments Performance Optimization on iphone OS Advanced Performance Optimization on iphone OS, Part 1 Advanced Performance Optimization on iphone OS, Part 2 Automating User Interface Testing with Instruments Presidio Wednesday 11:30AM Mission Thursday 9:00AM Presidio Thursday 2:00PM Mission Thursday 3:15PM Mission Friday 11:30AM Marina Wednesday 2:00PM 54

Labs iphone OS Performance Lab Mac OS X Performance Lab iphone OS Performance Lab iphone OS Performance Lab Mac OS X Performance Lab Application Frameworks Lab B Wednesday 9:00AM 11:15AM Developer Tools Lab A Tuesday 4:30 6:30PM Developer Tools Lab A Thursday 4:30PM 6:00PM Developer Tools Lab A Friday 9:00AM 11:15AM Application Frameworks Lab C Friday 11:30AM 1:00PM 55

56

57