SlideShare une entreprise Scribd logo
1  sur  58
Télécharger pour lire hors ligne
Managing and Optimizing
                      Memory Usage in iPhone
                           Applications
                                      Danton Chin
                           danton@iphonedeveloperjournal.com




                                           1
Wednesday, March 4, 2009
Intro
              Danton Chin

                     independent consultant

                           iPhone, Flex, AIR, Java development

                           experience in enterprise development and J2ME

                           blog at http://iphonedeveloperjournal.com/

                           email: danton at iphonedeveloperjournal dot com


                                              2
Wednesday, March 4, 2009
Agenda
                    100 level or introduction to managing memory

                           Broad understanding of the memory landscape

                    iPhone differences

                    Memory Management Model

                    Available tools for analyzing memory problems

                    Resources

                    Q&A


                                             3
Wednesday, March 4, 2009
It’s obvious but ...


                                        =

                                             images from http://www.apple.com/




                                    4
Wednesday, March 4, 2009
What are the
                             differences?
               CPU         Single core ARM chip (Samsung S5L8900)

                           • Limited
          Virtual          • No swap space
          Memory           • 128 MB shared with system and other
                             iPhone apps

              GPU          PowerVR MBX Lite (Imagination Technologies)
             Power         Battery
             Other         GPS chip (3G), etc.


                                          5
Wednesday, March 4, 2009
Big Job




                              6
Wednesday, March 4, 2009
7
Wednesday, March 4, 2009
Today




                             8
Wednesday, March 4, 2009
iPhone OS
                           variant of Mac OS X

                           128 MB

                             Virtual memory system is always on but
                           there is no swap file/space

                             Based on reports on the net your app may
                           be able to use up to ≈ 46 MB before you
                           run into a low memory condition

                           No GC

                             must use the managed memory model or
                           reference counting
                                             9
Wednesday, March 4, 2009
Two Stage Response to
                    Low Memory Condition
                     1. nonvolatile, static memory pages are removed
                     such as code pages

                           • volatile memory pages are never swapped
                           out

                     2. once free memory falls below a “certain
                     threshold” system will ask your application to
                     free up memory


                                             10
Wednesday, March 4, 2009
3 Ways to Register for
                     Memory Warnings: 1

         implement in your application delegate
    -(void) applicationDidReceiveMemoryWarning:(UIApplication *)application

    {

                 // release images, data structures, etc.

    }




                                                   11
Wednesday, March 4, 2009
3 Ways to Register for
                     Memory Warnings: 2
                     overrride in your UIViewController subclass

               -(void)didReceiveMemoryWarning:

               {

                           [super didReceiveMemoryWarning];

                           // release any views that are not needed

               }



                                              12
Wednesday, March 4, 2009
3 Ways to Register for
                     Memory Warnings: 3
         register to receive the notification

         UIApplicationDidReceiveMemoryWarningNotification
   ...
   [ [ NSNotificationCenter defaultCenter ]
       addObserver:self
           selector:@selector(appropriateMethodName:)
             name:UIApplicationDidReceiveMemoryWarningNotification
             object: nil ];
   ...




                                    13
Wednesday, March 4, 2009
Demo



                           Using the Simulator to simulate low memory




                                              14
Wednesday, March 4, 2009
applicationWillTerminate:

                                ka ... booom!


                     5..4..3..2..1..0


                               15
Wednesday, March 4, 2009
Application Memory Management and
                          Optimization Goals



                           Reduce the memory footprint of your
                           application

                           Eliminate memory leaks




                                              16
Wednesday, March 4, 2009
Reduce Memory Footprint
                           Load resources lazily

                           Reduce size of plists and images

                                 use the NSPropertyListSerialization class to
                                 write the property list file out in a binary
                                 format

                                 for images in PNG use pngcrush -iphone

                           Limit the amount of data in memory

                              Use SQLite

                           Use -mthumb compiler flag for apps without floating-
                           point calculations

                                                   17
Wednesday, March 4, 2009
Managed Memory Model



                           reference counting mechanism

                           ownership metaphor




                                                18
Wednesday, March 4, 2009
If you create it you own
                           it
                           alloc     reference count: + 1


                           copy      reference count: + 1


                           retain    reference count: + 1



                                    19
Wednesday, March 4, 2009
Relinquish Ownership
                                                        -1
                                      reference count
                       release

                                     reference count
                                     at some future
                      autorelease                       -1
                                               time
                                    point in



                                     20
Wednesday, March 4, 2009
When no one owns an
                            object ....

                             when
                                              destroyed/
                           reference
                                             deallocated/
                             count
                                            memory is freed
                            equals 0




                                       21
Wednesday, March 4, 2009
Recap




                           image from Scott Stevenson’s Learn Objective-C article at http://cocoadevcentral.com/d/learn_objectivec/




                                                                            22
Wednesday, March 4, 2009
Objective-C Gangsta Sign




                           by Flickr member Dirtae
                                      23
Wednesday, March 4, 2009
Dealloc
                     implement a dealloc method

                           release instance variables

                           invoke dealloc in superclass

                    -(void)dealloc
                    {
                       [ someInstanceVariable release];
                       [super dealloc];
                    }


                                               24
Wednesday, March 4, 2009
Convenience Constructors
                      object instances returned from convenience
                      constructors of the form +className... are NOT
                      owned by you and do not need to be released



                      NSString *string

                           = [ NSString stringWithFormat:@”360|iDev”;




                                           25
Wednesday, March 4, 2009
autorelease vs release:
                           Why Wait?

                           should be lazy about allocating memory

                           but we should not be lazy about releasing an
                           object once we are done with it

                             use release instead of autorelease when
                             you can



                                              26
Wednesday, March 4, 2009
Local Autorelease Pools
                           if you create a lot of temporary autoreleased
                           objects you may want to create a local
                           autorelease pool to reduce the memory
                           footprint of your app

                             autorelease pools are stacked

                                new pools are added to the top

                                autoreleased objects are added to the
                                top autorelease pool

                                drained/deallocated pools are removed
                                from the stack
                                               27
Wednesday, March 4, 2009
What can we use?



          Instruments            Shark
                                                Static
           Works on Simulator and                           Keep an eye
                                              analysis of
                  Device                                    on this one
                                                 code

                                                            Future may be able
                           Now                Early state    to write your own
                                         28
Wednesday, March 4, 2009
What tools don’t work?

                           MallocDebug, OpenGL Driver monitor, OpenGL
                           Profiler, Saturn, heap, leaks, vmmap

                           Activity Monitor, BigTop, Quartz Debug, Spin
                           Control, Thread Viewer, fs_usage, sc_usage,
                           top

                           gprof, malloc_history, vm_stat, otool,
                           pagestuff, and a few others


                                               29
Wednesday, March 4, 2009
Instruments
                           Xcode 3.0+, Mac OS X 10.5+

                           A trace document contains data gathered by
                           instruments

                             instruments are probes that collect data
                             about a specific performance metric

                             usually have less than ten instruments per
                             trace document

                           Launch from Xcode > Run > Start With
                           Performance Tool > Leaks

                                              30
Wednesday, March 4, 2009
Creating a Custom Trace
                             Document/Template
                     Instruments > File > New >




                                          31
Wednesday, March 4, 2009
Creating a Custom Trace
                         Document/Template




                                 32
Wednesday, March 4, 2009
Custom Trace Document/
                             Template                   iPhone instrument
                                                              library




                           Instruments > File > Save As Template
                                         33
Wednesday, March 4, 2009
Custom Trace Document Results




           inspector button
         for each instrument




                                        34
Wednesday, March 4, 2009
Inspector Windows




                           ObjectAlloc        Leaks inspector
                            inspector             window
                             window

                                         35
Wednesday, March 4, 2009
Toolbar

                                      playhead     Stack trace
   instruments pane Track pane
                                                 top


                           Detail pane
         View type
          selector:
            table,
           outline,
          diagram



                                         search bottom
                              36
Wednesday, March 4, 2009
ObjectAlloc: Table View




                                 37
Wednesday, March 4, 2009
Leaks Display:
                           Leaked Memory By
                             DiscoveryTime




                                  38
Wednesday, March 4, 2009
Demo




                            39
Wednesday, March 4, 2009
Clang Static Analyzer
                     LLVM (Low Level Virtual Machine) is the
                                                                 LLVM
                     parent project (http://llvm.org/) partially
                     funded by Apple and announced at WWDC in
                     2008

                           started by Chris Lattner in 2000
                                                                Clang
                     Clang is a sub-project and is the
                     C/C++/Objective-C front end to gcc

                     Clang Static Analyzer is a subproject of    Clang
                                                                 Static
                     Clang                                      Analyzer

                                             40
Wednesday, March 4, 2009
About


                           Performs a static analysis of your code

                           Wants to use the strengths of a compiler to
                           find bugs without test cases

                           Not a replacement for testing




                                               41
Wednesday, March 4, 2009
Goals

                           To find “deeper” bugs not merely syntactic
                           ones such as

                             memory leaks

                             buffer overruns

                             logic errors



                                               42
Wednesday, March 4, 2009
Benefits

                           Allow you to find bugs early

                           Open Source

                           Command line tool that could be integrated
                           into your own build process at some point
                           down the road



                                              43
Wednesday, March 4, 2009
Drawbacks
                           Very early in the development cycle -- the
                           version I used was at 0.167 with builds every
                           night

                           There are bugs

                           There are false positives or bugs that the
                           Clang Static Analyzer reports as bugs that
                           are not bugs

                           Needs more documentation

                                              44
Wednesday, March 4, 2009
Downloading and Installing
                           Download from http://clang.llvm.org/
                           StaticAnalysis.org

                           Installation is easy:

                             uncompress into your favorite folder

                             set the environmental variable for the
                             search path for your favorite shell




                                                   45
Wednesday, March 4, 2009
Using
            Easy to use

                   set the default directory to your project

                enter and execute the only command you need to
               know:

                           scan-build [command options] xcodebuild

                             scan-build is an executable script

                             xcodebuild part of Xcode

                                               46
Wednesday, March 4, 2009
Command Line Options
                           command options

                             -k keep on going to the build command
                             even if it fails

                             -v, -v -v, -v -v -v        verbosity levels

                             -V invokes scan-view

                             -plist outputs the results, if any, to a plist

                             --status-bugs causes scan-build to exit
                             with a 1 if bugs found or zero if none
                             found
                                                   47
Wednesday, March 4, 2009
Report Summary




                                 48
Wednesday, March 4, 2009
Report Detail




                                 49
Wednesday, March 4, 2009
Bottom Line



                           Very promising

                           Use it and get involved




                                               50
Wednesday, March 4, 2009
Resources
                   iPhone Memory

                           Memory on the iPhone http://vafer.org/blog/20081128082605

                           What the iPhone specs don’t tell you http://furbo.org/2007/08/21/what-
                           the-iphone-specs-dont-tell-you/

                   iPhone Application Programming Guide at http://developer.apple.com/iphone,
                   2008-10-15

                   Performance Overview: General, 2008-03-28 http://developer.apple.com/
                   iphone/library/documentation/Performance/Conceptual/
                   PerformanceOverview/PerformanceOverview.pdf




                                                        51
Wednesday, March 4, 2009
Resources

                           Apple Documentation on memory at http://developer.apple.com/
                           iphone/

                              Memory Usage Performance Guidelines, 2008-07-02

                              Memory Management Programming Guide for Cocoa, 2008-11-19

                              Memory Management Programming Guide for Core Foundation,
                              2008-10-15




                                                      52
Wednesday, March 4, 2009
Resources
                Memory Management

                      CS193P - Lecture 11: Performance, Stanford University at http://
                      www.stanford.edu/class/cs193p/cgi-bin/index.php

                      9 iphone Memory Management Links and Resources by Peter Cooper at
                      http://www.mobileorchard.com/iphone-memory-management

                      Memory Management by John Muchow at http:/  /macdevelopertips.com/
                      objective-c/objective-c-memory-management.html

                      Memory Management with Objective-C/Cocoa/iPhone by Mehmet Akten at
                      http://memo.tv/memory_management_with_objective_c_cocoa_iphone

                      Very Simple Rules for Memory Management in Cocoa by MMalcolm Crawford
                      at http://www.stepwise.com/Articles/Technical/2001-03-11.01.html

                      Learn Objective-C by Scott Stevenson http://cocoadevcentral.com/d/
                      learn_objectivec/


                                                     53
Wednesday, March 4, 2009
Resources

                           Memory Management Videos

                              Memory Management in Objective-C by Scotty at http://
                              www.mac-developer-network.com/category/videotraining/
                              beginner/ (not free)

                              Coding in Objective-C. Episode 2: Memory Management by Bill
                              Dudney at http://www.pragprog.com/screencasts/v-bdobjc/
                              coding-in-objective-c-2-0/ ($5)




                                                      54
Wednesday, March 4, 2009
Resources

                           Instruments

                             Instruments User Guide. Performance
                             Tuning: Instruments, http://
                             developer.apple.com/documentation/
                             DeveloperTools/Conceptual/
                             InstrumentsUserGuide/index.html



                                             55
Wednesday, March 4, 2009
Resources


                           Shark User Guide. Performance Tuning at
                           http://developer.apple.com/documentation/
                           DeveloperTools/Conceptual/SharkUserGuide/
                           index.html




                                             56
Wednesday, March 4, 2009
Resources
                 LLVM and Clang

                           LLVM home page at http://llvm.org/

                           Clang Static Analyzer home page at http://clang.llvm.org/
                           StaticAnalysis.html

                              setting the path varible for tsch and bash at http://
                              iphonedevelopment.blogspot.com/2009/02/clang-static-analyzer.html


                              LLVM Developer’s 2008 Meeting at http://llvm.org/devmtg/2008-08/

                                  Finding Bugs With the Clang Static Analyzer by Ted Kremenek, Apple
                                  Inc. Video and Slides (part of the link above)




                                                          57
Wednesday, March 4, 2009
Q&A




                            58
Wednesday, March 4, 2009

Contenu connexe

Similaire à Managing And Optimizing Memory Usage

IMC Summit 2016 Breakout - Gordon Patrick - Developments in Persistent Memory
IMC Summit 2016 Breakout - Gordon Patrick - Developments in Persistent MemoryIMC Summit 2016 Breakout - Gordon Patrick - Developments in Persistent Memory
IMC Summit 2016 Breakout - Gordon Patrick - Developments in Persistent MemoryIn-Memory Computing Summit
 
Firefox 3.5 and Beyond, At Portland Web Innovators
Firefox 3.5 and Beyond, At Portland Web InnovatorsFirefox 3.5 and Beyond, At Portland Web Innovators
Firefox 3.5 and Beyond, At Portland Web InnovatorsDietrich Ayala
 
Maven Application Lifecycle Management for Alfresco
Maven Application Lifecycle Management for AlfrescoMaven Application Lifecycle Management for Alfresco
Maven Application Lifecycle Management for Alfrescoguest67a9ba
 
Memory Management in Android
Memory Management in AndroidMemory Management in Android
Memory Management in AndroidOpersys inc.
 
AIM to Chat with Meebo: Logging onto Academic Advising
AIM to Chat with Meebo: Logging onto Academic AdvisingAIM to Chat with Meebo: Logging onto Academic Advising
AIM to Chat with Meebo: Logging onto Academic AdvisingMarissa Saenz
 
Debugging Native heap OOM - JavaOne 2013
Debugging Native heap OOM - JavaOne 2013Debugging Native heap OOM - JavaOne 2013
Debugging Native heap OOM - JavaOne 2013MattKilner
 
itsme Prototype Demo 2009-08-03
itsme Prototype Demo 2009-08-03itsme Prototype Demo 2009-08-03
itsme Prototype Demo 2009-08-03itsmesrl
 
Content Management Selection and Strategy
Content Management Selection and StrategyContent Management Selection and Strategy
Content Management Selection and StrategyIvo Jansch
 
Ibuildings Cms Talk
Ibuildings Cms TalkIbuildings Cms Talk
Ibuildings Cms Talkdean1985
 
Business Analytics Forum 2012 TM1 in Macquarie
Business Analytics Forum 2012 TM1 in MacquarieBusiness Analytics Forum 2012 TM1 in Macquarie
Business Analytics Forum 2012 TM1 in MacquarieAmendra Pratap
 
From Flash to iPhone
From Flash to iPhoneFrom Flash to iPhone
From Flash to iPhoneJohn Wilker
 
Memory Management in Android
Memory Management in AndroidMemory Management in Android
Memory Management in AndroidOpersys inc.
 
Memory Management in Android
Memory Management in AndroidMemory Management in Android
Memory Management in AndroidOpersys inc.
 
Memory card recovery
Memory card recoveryMemory card recovery
Memory card recoveryrose melley
 

Similaire à Managing And Optimizing Memory Usage (20)

Becoming Indie
Becoming IndieBecoming Indie
Becoming Indie
 
IMC Summit 2016 Breakout - Gordon Patrick - Developments in Persistent Memory
IMC Summit 2016 Breakout - Gordon Patrick - Developments in Persistent MemoryIMC Summit 2016 Breakout - Gordon Patrick - Developments in Persistent Memory
IMC Summit 2016 Breakout - Gordon Patrick - Developments in Persistent Memory
 
Firefox 3.5 and Beyond, At Portland Web Innovators
Firefox 3.5 and Beyond, At Portland Web InnovatorsFirefox 3.5 and Beyond, At Portland Web Innovators
Firefox 3.5 and Beyond, At Portland Web Innovators
 
ROM
ROMROM
ROM
 
Maven Application Lifecycle Management for Alfresco
Maven Application Lifecycle Management for AlfrescoMaven Application Lifecycle Management for Alfresco
Maven Application Lifecycle Management for Alfresco
 
Memory Management in Android
Memory Management in AndroidMemory Management in Android
Memory Management in Android
 
AIM to Chat with Meebo: Logging onto Academic Advising
AIM to Chat with Meebo: Logging onto Academic AdvisingAIM to Chat with Meebo: Logging onto Academic Advising
AIM to Chat with Meebo: Logging onto Academic Advising
 
Debugging Native heap OOM - JavaOne 2013
Debugging Native heap OOM - JavaOne 2013Debugging Native heap OOM - JavaOne 2013
Debugging Native heap OOM - JavaOne 2013
 
itsme Prototype Demo 2009-08-03
itsme Prototype Demo 2009-08-03itsme Prototype Demo 2009-08-03
itsme Prototype Demo 2009-08-03
 
rye.pdf
rye.pdfrye.pdf
rye.pdf
 
Content Management Selection and Strategy
Content Management Selection and StrategyContent Management Selection and Strategy
Content Management Selection and Strategy
 
Ibuildings Cms Talk
Ibuildings Cms TalkIbuildings Cms Talk
Ibuildings Cms Talk
 
Memory stick recovery
Memory stick recoveryMemory stick recovery
Memory stick recovery
 
Business Analytics Forum 2012 TM1 in Macquarie
Business Analytics Forum 2012 TM1 in MacquarieBusiness Analytics Forum 2012 TM1 in Macquarie
Business Analytics Forum 2012 TM1 in Macquarie
 
From Flash to iPhone
From Flash to iPhoneFrom Flash to iPhone
From Flash to iPhone
 
Memory unit
Memory unitMemory unit
Memory unit
 
Memory Management in Android
Memory Management in AndroidMemory Management in Android
Memory Management in Android
 
Memory Management in Android
Memory Management in AndroidMemory Management in Android
Memory Management in Android
 
Memory card recovery
Memory card recoveryMemory card recovery
Memory card recovery
 
Clean Code
Clean CodeClean Code
Clean Code
 

Plus de John Wilker

Cranking Floating Point Performance Up To 11
Cranking Floating Point Performance Up To 11Cranking Floating Point Performance Up To 11
Cranking Floating Point Performance Up To 11John Wilker
 
Introtoduction to cocos2d
Introtoduction to  cocos2dIntrotoduction to  cocos2d
Introtoduction to cocos2dJohn Wilker
 
Getting Started with OpenGL ES
Getting Started with OpenGL ESGetting Started with OpenGL ES
Getting Started with OpenGL ESJohn Wilker
 
User Input in a multi-touch, accelerometer, location aware world.
User Input in a multi-touch, accelerometer, location aware world.User Input in a multi-touch, accelerometer, location aware world.
User Input in a multi-touch, accelerometer, location aware world.John Wilker
 
Physics Solutions for Innovative Game Design
Physics Solutions for Innovative Game DesignPhysics Solutions for Innovative Game Design
Physics Solutions for Innovative Game DesignJohn Wilker
 
Getting Oriented with MapKit: Everything you need to get started with the new...
Getting Oriented with MapKit: Everything you need to get started with the new...Getting Oriented with MapKit: Everything you need to get started with the new...
Getting Oriented with MapKit: Everything you need to get started with the new...John Wilker
 
Getting Started with iPhone Game Development
Getting Started with iPhone Game DevelopmentGetting Started with iPhone Game Development
Getting Started with iPhone Game DevelopmentJohn Wilker
 
Internationalizing Your Apps
Internationalizing Your AppsInternationalizing Your Apps
Internationalizing Your AppsJohn Wilker
 
Optimizing Data Caching for iPhone Application Responsiveness
Optimizing Data Caching for iPhone Application ResponsivenessOptimizing Data Caching for iPhone Application Responsiveness
Optimizing Data Caching for iPhone Application ResponsivenessJohn Wilker
 
I Phone On Rails
I Phone On RailsI Phone On Rails
I Phone On RailsJohn Wilker
 
Integrating Push Notifications in your iPhone application with iLime
Integrating Push Notifications in your iPhone application with iLimeIntegrating Push Notifications in your iPhone application with iLime
Integrating Push Notifications in your iPhone application with iLimeJohn Wilker
 
Starting Core Animation
Starting Core AnimationStarting Core Animation
Starting Core AnimationJohn Wilker
 
P2P Multiplayer Gaming
P2P Multiplayer GamingP2P Multiplayer Gaming
P2P Multiplayer GamingJohn Wilker
 
Leaving Interface Builder Behind
Leaving Interface Builder BehindLeaving Interface Builder Behind
Leaving Interface Builder BehindJohn Wilker
 
Mobile WebKit Development and jQTouch
Mobile WebKit Development and jQTouchMobile WebKit Development and jQTouch
Mobile WebKit Development and jQTouchJohn Wilker
 
Accelerometer and OpenGL
Accelerometer and OpenGLAccelerometer and OpenGL
Accelerometer and OpenGLJohn Wilker
 
Deep Geek Diving into the iPhone OS and Framework
Deep Geek Diving into the iPhone OS and FrameworkDeep Geek Diving into the iPhone OS and Framework
Deep Geek Diving into the iPhone OS and FrameworkJohn Wilker
 
NSNotificationCenter vs. AppDelegate
NSNotificationCenter vs. AppDelegateNSNotificationCenter vs. AppDelegate
NSNotificationCenter vs. AppDelegateJohn Wilker
 
Using the Addressbook
Using the AddressbookUsing the Addressbook
Using the AddressbookJohn Wilker
 

Plus de John Wilker (20)

Cranking Floating Point Performance Up To 11
Cranking Floating Point Performance Up To 11Cranking Floating Point Performance Up To 11
Cranking Floating Point Performance Up To 11
 
Introtoduction to cocos2d
Introtoduction to  cocos2dIntrotoduction to  cocos2d
Introtoduction to cocos2d
 
Getting Started with OpenGL ES
Getting Started with OpenGL ESGetting Started with OpenGL ES
Getting Started with OpenGL ES
 
User Input in a multi-touch, accelerometer, location aware world.
User Input in a multi-touch, accelerometer, location aware world.User Input in a multi-touch, accelerometer, location aware world.
User Input in a multi-touch, accelerometer, location aware world.
 
Physics Solutions for Innovative Game Design
Physics Solutions for Innovative Game DesignPhysics Solutions for Innovative Game Design
Physics Solutions for Innovative Game Design
 
Getting Oriented with MapKit: Everything you need to get started with the new...
Getting Oriented with MapKit: Everything you need to get started with the new...Getting Oriented with MapKit: Everything you need to get started with the new...
Getting Oriented with MapKit: Everything you need to get started with the new...
 
Getting Started with iPhone Game Development
Getting Started with iPhone Game DevelopmentGetting Started with iPhone Game Development
Getting Started with iPhone Game Development
 
Internationalizing Your Apps
Internationalizing Your AppsInternationalizing Your Apps
Internationalizing Your Apps
 
Optimizing Data Caching for iPhone Application Responsiveness
Optimizing Data Caching for iPhone Application ResponsivenessOptimizing Data Caching for iPhone Application Responsiveness
Optimizing Data Caching for iPhone Application Responsiveness
 
I Phone On Rails
I Phone On RailsI Phone On Rails
I Phone On Rails
 
Integrating Push Notifications in your iPhone application with iLime
Integrating Push Notifications in your iPhone application with iLimeIntegrating Push Notifications in your iPhone application with iLime
Integrating Push Notifications in your iPhone application with iLime
 
Starting Core Animation
Starting Core AnimationStarting Core Animation
Starting Core Animation
 
P2P Multiplayer Gaming
P2P Multiplayer GamingP2P Multiplayer Gaming
P2P Multiplayer Gaming
 
Leaving Interface Builder Behind
Leaving Interface Builder BehindLeaving Interface Builder Behind
Leaving Interface Builder Behind
 
Mobile WebKit Development and jQTouch
Mobile WebKit Development and jQTouchMobile WebKit Development and jQTouch
Mobile WebKit Development and jQTouch
 
Accelerometer and OpenGL
Accelerometer and OpenGLAccelerometer and OpenGL
Accelerometer and OpenGL
 
Deep Geek Diving into the iPhone OS and Framework
Deep Geek Diving into the iPhone OS and FrameworkDeep Geek Diving into the iPhone OS and Framework
Deep Geek Diving into the iPhone OS and Framework
 
NSNotificationCenter vs. AppDelegate
NSNotificationCenter vs. AppDelegateNSNotificationCenter vs. AppDelegate
NSNotificationCenter vs. AppDelegate
 
Using SQLite
Using SQLiteUsing SQLite
Using SQLite
 
Using the Addressbook
Using the AddressbookUsing the Addressbook
Using the Addressbook
 

Dernier

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 

Dernier (20)

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 

Managing And Optimizing Memory Usage

  • 1. Managing and Optimizing Memory Usage in iPhone Applications Danton Chin danton@iphonedeveloperjournal.com 1 Wednesday, March 4, 2009
  • 2. Intro Danton Chin independent consultant iPhone, Flex, AIR, Java development experience in enterprise development and J2ME blog at http://iphonedeveloperjournal.com/ email: danton at iphonedeveloperjournal dot com 2 Wednesday, March 4, 2009
  • 3. Agenda 100 level or introduction to managing memory Broad understanding of the memory landscape iPhone differences Memory Management Model Available tools for analyzing memory problems Resources Q&A 3 Wednesday, March 4, 2009
  • 4. It’s obvious but ... = images from http://www.apple.com/ 4 Wednesday, March 4, 2009
  • 5. What are the differences? CPU Single core ARM chip (Samsung S5L8900) • Limited Virtual • No swap space Memory • 128 MB shared with system and other iPhone apps GPU PowerVR MBX Lite (Imagination Technologies) Power Battery Other GPS chip (3G), etc. 5 Wednesday, March 4, 2009
  • 6. Big Job 6 Wednesday, March 4, 2009
  • 8. Today 8 Wednesday, March 4, 2009
  • 9. iPhone OS variant of Mac OS X 128 MB Virtual memory system is always on but there is no swap file/space Based on reports on the net your app may be able to use up to ≈ 46 MB before you run into a low memory condition No GC must use the managed memory model or reference counting 9 Wednesday, March 4, 2009
  • 10. Two Stage Response to Low Memory Condition 1. nonvolatile, static memory pages are removed such as code pages • volatile memory pages are never swapped out 2. once free memory falls below a “certain threshold” system will ask your application to free up memory 10 Wednesday, March 4, 2009
  • 11. 3 Ways to Register for Memory Warnings: 1 implement in your application delegate -(void) applicationDidReceiveMemoryWarning:(UIApplication *)application { // release images, data structures, etc. } 11 Wednesday, March 4, 2009
  • 12. 3 Ways to Register for Memory Warnings: 2 overrride in your UIViewController subclass -(void)didReceiveMemoryWarning: { [super didReceiveMemoryWarning]; // release any views that are not needed } 12 Wednesday, March 4, 2009
  • 13. 3 Ways to Register for Memory Warnings: 3 register to receive the notification UIApplicationDidReceiveMemoryWarningNotification ... [ [ NSNotificationCenter defaultCenter ] addObserver:self selector:@selector(appropriateMethodName:) name:UIApplicationDidReceiveMemoryWarningNotification object: nil ]; ... 13 Wednesday, March 4, 2009
  • 14. Demo Using the Simulator to simulate low memory 14 Wednesday, March 4, 2009
  • 15. applicationWillTerminate: ka ... booom! 5..4..3..2..1..0 15 Wednesday, March 4, 2009
  • 16. Application Memory Management and Optimization Goals Reduce the memory footprint of your application Eliminate memory leaks 16 Wednesday, March 4, 2009
  • 17. Reduce Memory Footprint Load resources lazily Reduce size of plists and images use the NSPropertyListSerialization class to write the property list file out in a binary format for images in PNG use pngcrush -iphone Limit the amount of data in memory Use SQLite Use -mthumb compiler flag for apps without floating- point calculations 17 Wednesday, March 4, 2009
  • 18. Managed Memory Model reference counting mechanism ownership metaphor 18 Wednesday, March 4, 2009
  • 19. If you create it you own it alloc reference count: + 1 copy reference count: + 1 retain reference count: + 1 19 Wednesday, March 4, 2009
  • 20. Relinquish Ownership -1 reference count release reference count at some future autorelease -1 time point in 20 Wednesday, March 4, 2009
  • 21. When no one owns an object .... when destroyed/ reference deallocated/ count memory is freed equals 0 21 Wednesday, March 4, 2009
  • 22. Recap image from Scott Stevenson’s Learn Objective-C article at http://cocoadevcentral.com/d/learn_objectivec/ 22 Wednesday, March 4, 2009
  • 23. Objective-C Gangsta Sign by Flickr member Dirtae 23 Wednesday, March 4, 2009
  • 24. Dealloc implement a dealloc method release instance variables invoke dealloc in superclass -(void)dealloc { [ someInstanceVariable release]; [super dealloc]; } 24 Wednesday, March 4, 2009
  • 25. Convenience Constructors object instances returned from convenience constructors of the form +className... are NOT owned by you and do not need to be released NSString *string = [ NSString stringWithFormat:@”360|iDev”; 25 Wednesday, March 4, 2009
  • 26. autorelease vs release: Why Wait? should be lazy about allocating memory but we should not be lazy about releasing an object once we are done with it use release instead of autorelease when you can 26 Wednesday, March 4, 2009
  • 27. Local Autorelease Pools if you create a lot of temporary autoreleased objects you may want to create a local autorelease pool to reduce the memory footprint of your app autorelease pools are stacked new pools are added to the top autoreleased objects are added to the top autorelease pool drained/deallocated pools are removed from the stack 27 Wednesday, March 4, 2009
  • 28. What can we use? Instruments Shark Static Works on Simulator and Keep an eye analysis of Device on this one code Future may be able Now Early state to write your own 28 Wednesday, March 4, 2009
  • 29. What tools don’t work? MallocDebug, OpenGL Driver monitor, OpenGL Profiler, Saturn, heap, leaks, vmmap Activity Monitor, BigTop, Quartz Debug, Spin Control, Thread Viewer, fs_usage, sc_usage, top gprof, malloc_history, vm_stat, otool, pagestuff, and a few others 29 Wednesday, March 4, 2009
  • 30. Instruments Xcode 3.0+, Mac OS X 10.5+ A trace document contains data gathered by instruments instruments are probes that collect data about a specific performance metric usually have less than ten instruments per trace document Launch from Xcode > Run > Start With Performance Tool > Leaks 30 Wednesday, March 4, 2009
  • 31. Creating a Custom Trace Document/Template Instruments > File > New > 31 Wednesday, March 4, 2009
  • 32. Creating a Custom Trace Document/Template 32 Wednesday, March 4, 2009
  • 33. Custom Trace Document/ Template iPhone instrument library Instruments > File > Save As Template 33 Wednesday, March 4, 2009
  • 34. Custom Trace Document Results inspector button for each instrument 34 Wednesday, March 4, 2009
  • 35. Inspector Windows ObjectAlloc Leaks inspector inspector window window 35 Wednesday, March 4, 2009
  • 36. Toolbar playhead Stack trace instruments pane Track pane top Detail pane View type selector: table, outline, diagram search bottom 36 Wednesday, March 4, 2009
  • 37. ObjectAlloc: Table View 37 Wednesday, March 4, 2009
  • 38. Leaks Display: Leaked Memory By DiscoveryTime 38 Wednesday, March 4, 2009
  • 39. Demo 39 Wednesday, March 4, 2009
  • 40. Clang Static Analyzer LLVM (Low Level Virtual Machine) is the LLVM parent project (http://llvm.org/) partially funded by Apple and announced at WWDC in 2008 started by Chris Lattner in 2000 Clang Clang is a sub-project and is the C/C++/Objective-C front end to gcc Clang Static Analyzer is a subproject of Clang Static Clang Analyzer 40 Wednesday, March 4, 2009
  • 41. About Performs a static analysis of your code Wants to use the strengths of a compiler to find bugs without test cases Not a replacement for testing 41 Wednesday, March 4, 2009
  • 42. Goals To find “deeper” bugs not merely syntactic ones such as memory leaks buffer overruns logic errors 42 Wednesday, March 4, 2009
  • 43. Benefits Allow you to find bugs early Open Source Command line tool that could be integrated into your own build process at some point down the road 43 Wednesday, March 4, 2009
  • 44. Drawbacks Very early in the development cycle -- the version I used was at 0.167 with builds every night There are bugs There are false positives or bugs that the Clang Static Analyzer reports as bugs that are not bugs Needs more documentation 44 Wednesday, March 4, 2009
  • 45. Downloading and Installing Download from http://clang.llvm.org/ StaticAnalysis.org Installation is easy: uncompress into your favorite folder set the environmental variable for the search path for your favorite shell 45 Wednesday, March 4, 2009
  • 46. Using Easy to use set the default directory to your project enter and execute the only command you need to know: scan-build [command options] xcodebuild scan-build is an executable script xcodebuild part of Xcode 46 Wednesday, March 4, 2009
  • 47. Command Line Options command options -k keep on going to the build command even if it fails -v, -v -v, -v -v -v verbosity levels -V invokes scan-view -plist outputs the results, if any, to a plist --status-bugs causes scan-build to exit with a 1 if bugs found or zero if none found 47 Wednesday, March 4, 2009
  • 48. Report Summary 48 Wednesday, March 4, 2009
  • 49. Report Detail 49 Wednesday, March 4, 2009
  • 50. Bottom Line Very promising Use it and get involved 50 Wednesday, March 4, 2009
  • 51. Resources iPhone Memory Memory on the iPhone http://vafer.org/blog/20081128082605 What the iPhone specs don’t tell you http://furbo.org/2007/08/21/what- the-iphone-specs-dont-tell-you/ iPhone Application Programming Guide at http://developer.apple.com/iphone, 2008-10-15 Performance Overview: General, 2008-03-28 http://developer.apple.com/ iphone/library/documentation/Performance/Conceptual/ PerformanceOverview/PerformanceOverview.pdf 51 Wednesday, March 4, 2009
  • 52. Resources Apple Documentation on memory at http://developer.apple.com/ iphone/ Memory Usage Performance Guidelines, 2008-07-02 Memory Management Programming Guide for Cocoa, 2008-11-19 Memory Management Programming Guide for Core Foundation, 2008-10-15 52 Wednesday, March 4, 2009
  • 53. Resources Memory Management CS193P - Lecture 11: Performance, Stanford University at http:// www.stanford.edu/class/cs193p/cgi-bin/index.php 9 iphone Memory Management Links and Resources by Peter Cooper at http://www.mobileorchard.com/iphone-memory-management Memory Management by John Muchow at http:/ /macdevelopertips.com/ objective-c/objective-c-memory-management.html Memory Management with Objective-C/Cocoa/iPhone by Mehmet Akten at http://memo.tv/memory_management_with_objective_c_cocoa_iphone Very Simple Rules for Memory Management in Cocoa by MMalcolm Crawford at http://www.stepwise.com/Articles/Technical/2001-03-11.01.html Learn Objective-C by Scott Stevenson http://cocoadevcentral.com/d/ learn_objectivec/ 53 Wednesday, March 4, 2009
  • 54. Resources Memory Management Videos Memory Management in Objective-C by Scotty at http:// www.mac-developer-network.com/category/videotraining/ beginner/ (not free) Coding in Objective-C. Episode 2: Memory Management by Bill Dudney at http://www.pragprog.com/screencasts/v-bdobjc/ coding-in-objective-c-2-0/ ($5) 54 Wednesday, March 4, 2009
  • 55. Resources Instruments Instruments User Guide. Performance Tuning: Instruments, http:// developer.apple.com/documentation/ DeveloperTools/Conceptual/ InstrumentsUserGuide/index.html 55 Wednesday, March 4, 2009
  • 56. Resources Shark User Guide. Performance Tuning at http://developer.apple.com/documentation/ DeveloperTools/Conceptual/SharkUserGuide/ index.html 56 Wednesday, March 4, 2009
  • 57. Resources LLVM and Clang LLVM home page at http://llvm.org/ Clang Static Analyzer home page at http://clang.llvm.org/ StaticAnalysis.html setting the path varible for tsch and bash at http:// iphonedevelopment.blogspot.com/2009/02/clang-static-analyzer.html LLVM Developer’s 2008 Meeting at http://llvm.org/devmtg/2008-08/ Finding Bugs With the Clang Static Analyzer by Ted Kremenek, Apple Inc. Video and Slides (part of the link above) 57 Wednesday, March 4, 2009
  • 58. Q&A 58 Wednesday, March 4, 2009