SlideShare a Scribd company logo
1 of 72
Download to read offline
HELP, MY XAMARIN APP HAS
MEMORY ISSUES!
About the speaker
Pieter Nijs
Senior .NET Consultant & Competence Lead Mobile
@ Ordina Belgium
Microsoft MVP Windows Development
MADN Board Member
Blog.PieEatingNinjas.be
@nijspieter
ORDINA
Who are our enemies today?
Memory issues
# 1 Get to know our enemy (high level)
# 1 Get to know our enemy (in general)
What is a memory leak?
Objects that are not being removed from memory, although
they are not needed any more (not accessible from code).
# 1 Get to know our enemy (in general)
What about our ‘secret’ weapon, the GC?
# 1 Get to know our enemy (in general)
What about our ‘secret’ weapon, the GC?
• Us protecting our enemies
• Framework
• Coding
• Managed Mono memory is
only part of the entire memory
# 1 Get to know our enemy (in general)
The main ’problem’ with Xamarin
• 2 different types of memory
Mono
runtime
# 1 Get to know our enemy (in general)
The main ’problem’ with Xamarin
• 2 different types of memory è objects living in both ‘worlds’
UIButton button = new UIButton(); [UIButton]
UIButton
# 2 Pick the right gear
# 2 Pick the right gear
Profilers
• Instruments
• Xamarin Profiler
• Android Profiler
• …
# 2 Pick the right gear
Let code guide you
• Finalizers
• Weak References
• Output window
• …
# 2 Pick the right gear
Our superior developer’s brain
• THINK!!
• Look for high numbers when profiling
• Use your .NET / C# knowledge
• …
# 3 Let’s do this!
First encounter: Xamarin iOS
Get to know our enemy: Xamarin iOS
Get to know our enemy: Xamarin iOS
General .NET pitfall we already know
Delegates and events live as long as the publisher
è Problem when publisher lives longer than
subscriber
è NSNotificationCenter
è Except: events/actions set via Storyboard
Get to know our enemy: Xamarin iOS
How does iOS manages memory?
Reference counting
Get to know our enemy: Xamarin iOS
Reference counting
Instantiate:
[[Person alloc] init] è retain count 1
Copy reference:
Person2 = [Person retain] è retain count 2
Release:
[Person release] è retain count 1
[Person2 release] è retain count 0
Get to know our enemy: Xamarin iOS
Peer objects
Get to know our enemy: Xamarin iOS
Peer objects
Managed wrappers around native iOS objects when accessed
by Xamarin.iOS runtime.
Get to know our enemy: Xamarin iOS
Native iOS
Native object
[UIButton]
Native memory
Allocated by iOS
Reference count
Xamarin.iOS
Peer object
UIKit.UIButton
Managed memory
Allocated by X.iOS
Collected by GC
IntPtr Handle
Peer objects
Get to know our enemy: Xamarin iOS
Peer objects
Native iOS
[[UIButton alloc] init]
[b release]
[b release]
Xamarin.iOS
var b = new UIButton(…);
b = null;
b.Dispose();
Release in finalizer,
using IntPtr
Get to know our enemy: Xamarin iOS
Framework peers User peers
Peer objects
Get to know our enemy: Xamarin iOS
Framework peers
• Built-in types around iOS objects
• Stateless
è call native objects to get or set values
è Lots of optimizations by the framework
• Created first time C# code accesses the object
• Can be created on the fly
• …
Get to know our enemy: Xamarin iOS
User peers
• Custom type deriving from Framework peer
• Have state!
public class MyCustomView : UIKit.UIView
{
public string Text
{
get;
set;
}
}
Get to know our enemy: Xamarin iOS
User peers
• Have state!
èiOS doesn’t know about this additional state
èNeeds to be kept alive on managed side
Get to know our enemy: Xamarin iOS
User peers
• Have state!
View.AddSubview(new MyCustomView()
{ Text = "Hello Techorama" });
…
if (View.Subviews.Last() is MyCustomView mcv)
Debug.WriteLine(mcv.Text);
Get to know our enemy: Xamarin iOS
User peers - State
• Xamarin.iOS ROOTS User peer objects that have no managed
references
MyCustomView UIView
Get to know our enemy: Xamarin iOS
User peers - State
• Xamarin.iOS ROOTS User peer objects that have no managed
references
MyCustomView UIView
GC Handle
Get to know our enemy: Xamarin iOS
User peers - State
• GC will look at the retain count of native object
• Retain Count > 1
è Object is alive and kicking
• Retain Count == 1 && no references to managed object
è Managed object can be collected
Get to know our enemy: Xamarin iOS
User peers - State
Strong references added by the framework, outside
our code, can easily create a reference cycle
that can NOT be broken by the GC!
Get to know our enemy: Xamarin iOS
User peers - Reference cycle
GalleryImageView UIView
GC Handle
GalleryViewController UIViewController Retain count = 2
Retain count = 2
Managed reference
View.AddSubview(new GalleryImageView(this));
Get to know our enemy: Xamarin iOS
User peers - Reference cycle
When we navigate back, we get this:
GalleryImageView UIView
GC Handle
GalleryViewController UIViewController Retain count = 1
Retain count = 2
Get to know our enemy: Xamarin iOS
User peers - Reference cycle
When we navigate back, we get this:
GalleryImageView UIView
GC Handle
GalleryViewController UIViewController Retain count = 1
Retain count = 2
Managed reference is still here!!
Get to know our enemy: Xamarin iOS
User peers - Reference cycle
We need to break the cycle when navigating back:
GalleryImageView UIView
GC Handle
GalleryViewController UIViewController Retain count = 1
Retain count = 1
_galleryViewController = null;
Retain count = 2
Get to know our enemy: Xamarin iOS
Peer promotion
Framework peer being promoted to User peer
_galleryButton = new UIButton();
…
_galleryButton.TouchUpInside += GalleryButton_TouchUpInside;
è Adding state
è Reference cycles!
Get to know our enemy: Xamarin iOS
Peer promotion
Unsubscribe from events (or use storyboard actions)
public override void ViewDidAppear(bool animated)
{
EvilButton.TouchUpInside += EvilButton_TouchUpInside;
}
public override void ViewDidDisappear(bool animated)
{
EvilButton.TouchUpInside -= EvilButton_TouchUpInside;
}
Xamarin iOS Battleplan
Xamarin iOS Battleplan
è Unsubscribe from delegates and events!
Except for events/actions set via Storyboard
è Call Dispose() on big peers when needed
(instead of waiting for GC)
è Manually break reference cycles
First encounter: Xamarin iOS
DEMO
Second encounter: Xamarin Android
Get to know our enemy: Xamarin Android
Get to know our enemy: Xamarin Android
How does Android manages memory?
GC
Get to know our enemy: Xamarin Android
Garbage Collectors
Both GCs need to work together
Get to know our enemy: Xamarin Android
Remember Peer objects ?
Get to know our enemy: Xamarin Android
Peer objects
Native Android / Java
Native object
Java.Lang.Object
JVM memory
Allocated by JVM
Collected by
Android GC
Xamarin.Android
Peer object
IJavaObject
Managed memory
Allocated by X.Droid
Collected by GC
IntPtr Handle JNI Handle
Treated as GC root by JVM
Get to know our enemy: Xamarin Android
Garbage Collection
‘Normal’ managed objects
è ‘Classic’ GC
Peer Objects
è JNI Handle replaced with Weak Handle
è Force Android / Java GC
è Weak reference != Alive? è Collect
Get to know our enemy: Xamarin Android
Garbage Collection
Good and bad news…
The good: No reference cycle problems as in iOS
The bad: GC takes longer & higher memory pressure
Get to know our enemy: Xamarin Android
Watch out for bitmaps
Typically large objects, but not on the Mono-side
è Possible no Mono GC will occur
è Android GC can’t collect due to active JNI handle
Get to know our enemy: Xamarin Android
Boxing
ArrayAdapter is a Framework peer, using java.util.ArrayList
internally, holding references to Java objects
è C# objects are boxed to create Java representation
Xamarin Android Battleplan
Xamarin Android Battleplan
è Improve GC performance
• Dispose peer objects & set references to null
• Periodically trigger a GC
è Watch out for Bitmaps, use Dispose/using
è Avoid using ArrayAdapter, use BaseAdapter instead
è Experiment with ‘new’ GC Bridges
Xamarin Android Battleplan
GC Bridge
Integration between
Xamarin GC & JVM GC
JVM
Mono
Xamarin Android Battleplan
GC Bridge
Default: ‘Old’ bridge
Alternatives: ‘New’ and ’Tarjan’
Newer implementations != silver bullet
è Experimental, but might work for you
è Try it out and test!
Second encounter: Xamarin Android
DEMO
Third encounter: Xamarin Forms
Get to know our enemy: Xamarin Forms
Get to know our enemy: Xamarin Forms
Can be both easiest and hardest enemy!
General .NET pitfall we already know:
Delegates and events
Xamarin Forms, ‘knows’ about previous platform-specific
pitfalls and takes them into account.
BUT all iOS & Droid specific caveats are relevant on effects
and renderers!
Third encounter: Xamarin Forms
DEMO
Techorama
Questions?
Thank you!
ORDINA

More Related Content

Similar to Techorama 2018 - Help my Xamarin app has memory issues! - Pieter Nijs

C# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCross
C# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCrossC# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCross
C# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCrossFlavius-Radu Demian
 
Profiling JavaScript Performance
Profiling JavaScript PerformanceProfiling JavaScript Performance
Profiling JavaScript PerformanceNoam Kfir
 
Mobile development strategies with MVVM
Mobile development strategies with MVVMMobile development strategies with MVVM
Mobile development strategies with MVVMJames Montemagno
 
Augmented reality for consumer devices
Augmented reality for consumer devicesAugmented reality for consumer devices
Augmented reality for consumer devicesjbienz
 
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo KumperaAdvanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo KumperaXamarin
 
Evovle 2016 - Everyone Can Create Beautiful Apps with Material Design
Evovle 2016 - Everyone Can Create Beautiful Apps with Material DesignEvovle 2016 - Everyone Can Create Beautiful Apps with Material Design
Evovle 2016 - Everyone Can Create Beautiful Apps with Material DesignJames Montemagno
 
Cross-Platform UI Controls, Andrey Baskov
Cross-Platform UI Controls, Andrey BaskovCross-Platform UI Controls, Andrey Baskov
Cross-Platform UI Controls, Andrey BaskovXamarin
 
Las Vegas Code Camp - iOS Development in C# with Xamarin
Las Vegas Code Camp -  iOS Development in C# with XamarinLas Vegas Code Camp -  iOS Development in C# with Xamarin
Las Vegas Code Camp - iOS Development in C# with XamarinJames Montemagno
 
Dragons & Knights - Calabash and Cucumber as Automation Tools for Hybrid Apps...
Dragons & Knights - Calabash and Cucumber as Automation Tools for Hybrid Apps...Dragons & Knights - Calabash and Cucumber as Automation Tools for Hybrid Apps...
Dragons & Knights - Calabash and Cucumber as Automation Tools for Hybrid Apps...Ron Werner
 
Top Tips for Android UIs - Getting the Magic on Tablets
Top Tips for Android UIs - Getting the Magic on TabletsTop Tips for Android UIs - Getting the Magic on Tablets
Top Tips for Android UIs - Getting the Magic on TabletsMotorola Mobility - MOTODEV
 
iOS Programming - MCV (Delegate/Protocols/Property&Syntax)
iOS Programming - MCV (Delegate/Protocols/Property&Syntax)iOS Programming - MCV (Delegate/Protocols/Property&Syntax)
iOS Programming - MCV (Delegate/Protocols/Property&Syntax)Oliver Lin
 
A Multiplatform, Multi-Tenant Challenge - Droidcon Lisbon 2023
A Multiplatform, Multi-Tenant Challenge - Droidcon Lisbon 2023A Multiplatform, Multi-Tenant Challenge - Droidcon Lisbon 2023
A Multiplatform, Multi-Tenant Challenge - Droidcon Lisbon 2023Pedro Vicente
 
extending-and-optimizing-xamarin-forms-apps
extending-and-optimizing-xamarin-forms-appsextending-and-optimizing-xamarin-forms-apps
extending-and-optimizing-xamarin-forms-appsMatthew Soucoup
 
Beware the potholes on the road to serverless
Beware the potholes on the road to serverlessBeware the potholes on the road to serverless
Beware the potholes on the road to serverlessYan Cui
 
Mono for Android... for Google Devs
Mono for Android... for Google DevsMono for Android... for Google Devs
Mono for Android... for Google DevsCraig Dunn
 
HitCon'14: On the Feasibility of Automatically Generating Android Component H...
HitCon'14: On the Feasibility of Automatically Generating Android Component H...HitCon'14: On the Feasibility of Automatically Generating Android Component H...
HitCon'14: On the Feasibility of Automatically Generating Android Component H...daoyuan0x
 
SmartDevCon - Katowice - 2013
SmartDevCon - Katowice - 2013SmartDevCon - Katowice - 2013
SmartDevCon - Katowice - 2013Petr Dvorak
 
Android Internals (This is not the droid you’re loking for...)
Android Internals (This is not the droid you’re loking for...)Android Internals (This is not the droid you’re loking for...)
Android Internals (This is not the droid you’re loking for...)Giacomo Bergami
 
Build 2017 - B8099 - What's new in Xamarin.Forms
Build 2017 - B8099 - What's new in Xamarin.FormsBuild 2017 - B8099 - What's new in Xamarin.Forms
Build 2017 - B8099 - What's new in Xamarin.FormsWindows Developer
 
Attacks and Defences
Attacks and DefencesAttacks and Defences
Attacks and DefencesSensePost
 

Similar to Techorama 2018 - Help my Xamarin app has memory issues! - Pieter Nijs (20)

C# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCross
C# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCrossC# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCross
C# everywhere - Building Cross-Platform Apps with Xamarin and MvvmCross
 
Profiling JavaScript Performance
Profiling JavaScript PerformanceProfiling JavaScript Performance
Profiling JavaScript Performance
 
Mobile development strategies with MVVM
Mobile development strategies with MVVMMobile development strategies with MVVM
Mobile development strategies with MVVM
 
Augmented reality for consumer devices
Augmented reality for consumer devicesAugmented reality for consumer devices
Augmented reality for consumer devices
 
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo KumperaAdvanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
Advanced Memory Management on iOS and Android - Mark Probst and Rodrigo Kumpera
 
Evovle 2016 - Everyone Can Create Beautiful Apps with Material Design
Evovle 2016 - Everyone Can Create Beautiful Apps with Material DesignEvovle 2016 - Everyone Can Create Beautiful Apps with Material Design
Evovle 2016 - Everyone Can Create Beautiful Apps with Material Design
 
Cross-Platform UI Controls, Andrey Baskov
Cross-Platform UI Controls, Andrey BaskovCross-Platform UI Controls, Andrey Baskov
Cross-Platform UI Controls, Andrey Baskov
 
Las Vegas Code Camp - iOS Development in C# with Xamarin
Las Vegas Code Camp -  iOS Development in C# with XamarinLas Vegas Code Camp -  iOS Development in C# with Xamarin
Las Vegas Code Camp - iOS Development in C# with Xamarin
 
Dragons & Knights - Calabash and Cucumber as Automation Tools for Hybrid Apps...
Dragons & Knights - Calabash and Cucumber as Automation Tools for Hybrid Apps...Dragons & Knights - Calabash and Cucumber as Automation Tools for Hybrid Apps...
Dragons & Knights - Calabash and Cucumber as Automation Tools for Hybrid Apps...
 
Top Tips for Android UIs - Getting the Magic on Tablets
Top Tips for Android UIs - Getting the Magic on TabletsTop Tips for Android UIs - Getting the Magic on Tablets
Top Tips for Android UIs - Getting the Magic on Tablets
 
iOS Programming - MCV (Delegate/Protocols/Property&Syntax)
iOS Programming - MCV (Delegate/Protocols/Property&Syntax)iOS Programming - MCV (Delegate/Protocols/Property&Syntax)
iOS Programming - MCV (Delegate/Protocols/Property&Syntax)
 
A Multiplatform, Multi-Tenant Challenge - Droidcon Lisbon 2023
A Multiplatform, Multi-Tenant Challenge - Droidcon Lisbon 2023A Multiplatform, Multi-Tenant Challenge - Droidcon Lisbon 2023
A Multiplatform, Multi-Tenant Challenge - Droidcon Lisbon 2023
 
extending-and-optimizing-xamarin-forms-apps
extending-and-optimizing-xamarin-forms-appsextending-and-optimizing-xamarin-forms-apps
extending-and-optimizing-xamarin-forms-apps
 
Beware the potholes on the road to serverless
Beware the potholes on the road to serverlessBeware the potholes on the road to serverless
Beware the potholes on the road to serverless
 
Mono for Android... for Google Devs
Mono for Android... for Google DevsMono for Android... for Google Devs
Mono for Android... for Google Devs
 
HitCon'14: On the Feasibility of Automatically Generating Android Component H...
HitCon'14: On the Feasibility of Automatically Generating Android Component H...HitCon'14: On the Feasibility of Automatically Generating Android Component H...
HitCon'14: On the Feasibility of Automatically Generating Android Component H...
 
SmartDevCon - Katowice - 2013
SmartDevCon - Katowice - 2013SmartDevCon - Katowice - 2013
SmartDevCon - Katowice - 2013
 
Android Internals (This is not the droid you’re loking for...)
Android Internals (This is not the droid you’re loking for...)Android Internals (This is not the droid you’re loking for...)
Android Internals (This is not the droid you’re loking for...)
 
Build 2017 - B8099 - What's new in Xamarin.Forms
Build 2017 - B8099 - What's new in Xamarin.FormsBuild 2017 - B8099 - What's new in Xamarin.Forms
Build 2017 - B8099 - What's new in Xamarin.Forms
 
Attacks and Defences
Attacks and DefencesAttacks and Defences
Attacks and Defences
 

More from N Core

Techorama 2018 - Elasticsearch - search done right - Bart Wullems
Techorama 2018 - Elasticsearch - search done right - Bart WullemsTechorama 2018 - Elasticsearch - search done right - Bart Wullems
Techorama 2018 - Elasticsearch - search done right - Bart WullemsN Core
 
uNite 2017 - Going serverless - Gertjan Vanthienen
uNite 2017 - Going serverless - Gertjan VanthienenuNite 2017 - Going serverless - Gertjan Vanthienen
uNite 2017 - Going serverless - Gertjan VanthienenN Core
 
Unite 2017 - CQRS - Jens Gheerardyn
Unite 2017 - CQRS - Jens GheerardynUnite 2017 - CQRS - Jens Gheerardyn
Unite 2017 - CQRS - Jens GheerardynN Core
 
uNite 2017 - Magic mirror - Tom Vandevoorde and Michiel Wouters
uNite 2017 - Magic mirror - Tom Vandevoorde and Michiel WoutersuNite 2017 - Magic mirror - Tom Vandevoorde and Michiel Wouters
uNite 2017 - Magic mirror - Tom Vandevoorde and Michiel WoutersN Core
 
Unite 2017 - Elastic Eearch - Bart Wullems
Unite 2017 - Elastic Eearch - Bart WullemsUnite 2017 - Elastic Eearch - Bart Wullems
Unite 2017 - Elastic Eearch - Bart WullemsN Core
 
Unite 2017 - Reactive Programming - Pieter Nijs
Unite 2017 - Reactive Programming - Pieter NijsUnite 2017 - Reactive Programming - Pieter Nijs
Unite 2017 - Reactive Programming - Pieter NijsN Core
 

More from N Core (6)

Techorama 2018 - Elasticsearch - search done right - Bart Wullems
Techorama 2018 - Elasticsearch - search done right - Bart WullemsTechorama 2018 - Elasticsearch - search done right - Bart Wullems
Techorama 2018 - Elasticsearch - search done right - Bart Wullems
 
uNite 2017 - Going serverless - Gertjan Vanthienen
uNite 2017 - Going serverless - Gertjan VanthienenuNite 2017 - Going serverless - Gertjan Vanthienen
uNite 2017 - Going serverless - Gertjan Vanthienen
 
Unite 2017 - CQRS - Jens Gheerardyn
Unite 2017 - CQRS - Jens GheerardynUnite 2017 - CQRS - Jens Gheerardyn
Unite 2017 - CQRS - Jens Gheerardyn
 
uNite 2017 - Magic mirror - Tom Vandevoorde and Michiel Wouters
uNite 2017 - Magic mirror - Tom Vandevoorde and Michiel WoutersuNite 2017 - Magic mirror - Tom Vandevoorde and Michiel Wouters
uNite 2017 - Magic mirror - Tom Vandevoorde and Michiel Wouters
 
Unite 2017 - Elastic Eearch - Bart Wullems
Unite 2017 - Elastic Eearch - Bart WullemsUnite 2017 - Elastic Eearch - Bart Wullems
Unite 2017 - Elastic Eearch - Bart Wullems
 
Unite 2017 - Reactive Programming - Pieter Nijs
Unite 2017 - Reactive Programming - Pieter NijsUnite 2017 - Reactive Programming - Pieter Nijs
Unite 2017 - Reactive Programming - Pieter Nijs
 

Recently uploaded

%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyAnusha Are
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park masabamasaba
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456KiaraTiradoMicha
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 

Recently uploaded (20)

%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodology
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 

Techorama 2018 - Help my Xamarin app has memory issues! - Pieter Nijs

  • 1. HELP, MY XAMARIN APP HAS MEMORY ISSUES!
  • 2. About the speaker Pieter Nijs Senior .NET Consultant & Competence Lead Mobile @ Ordina Belgium Microsoft MVP Windows Development MADN Board Member Blog.PieEatingNinjas.be @nijspieter
  • 4.
  • 5.
  • 6.
  • 7.
  • 8. Who are our enemies today? Memory issues
  • 9. # 1 Get to know our enemy (high level)
  • 10. # 1 Get to know our enemy (in general) What is a memory leak? Objects that are not being removed from memory, although they are not needed any more (not accessible from code).
  • 11. # 1 Get to know our enemy (in general) What about our ‘secret’ weapon, the GC?
  • 12. # 1 Get to know our enemy (in general) What about our ‘secret’ weapon, the GC? • Us protecting our enemies • Framework • Coding • Managed Mono memory is only part of the entire memory
  • 13. # 1 Get to know our enemy (in general) The main ’problem’ with Xamarin • 2 different types of memory Mono runtime
  • 14. # 1 Get to know our enemy (in general) The main ’problem’ with Xamarin • 2 different types of memory è objects living in both ‘worlds’ UIButton button = new UIButton(); [UIButton] UIButton
  • 15. # 2 Pick the right gear
  • 16. # 2 Pick the right gear Profilers • Instruments • Xamarin Profiler • Android Profiler • …
  • 17. # 2 Pick the right gear Let code guide you • Finalizers • Weak References • Output window • …
  • 18. # 2 Pick the right gear Our superior developer’s brain • THINK!! • Look for high numbers when profiling • Use your .NET / C# knowledge • …
  • 19. # 3 Let’s do this!
  • 21. Get to know our enemy: Xamarin iOS
  • 22. Get to know our enemy: Xamarin iOS General .NET pitfall we already know Delegates and events live as long as the publisher è Problem when publisher lives longer than subscriber è NSNotificationCenter è Except: events/actions set via Storyboard
  • 23. Get to know our enemy: Xamarin iOS How does iOS manages memory? Reference counting
  • 24. Get to know our enemy: Xamarin iOS Reference counting Instantiate: [[Person alloc] init] è retain count 1 Copy reference: Person2 = [Person retain] è retain count 2 Release: [Person release] è retain count 1 [Person2 release] è retain count 0
  • 25. Get to know our enemy: Xamarin iOS Peer objects
  • 26. Get to know our enemy: Xamarin iOS Peer objects Managed wrappers around native iOS objects when accessed by Xamarin.iOS runtime.
  • 27. Get to know our enemy: Xamarin iOS Native iOS Native object [UIButton] Native memory Allocated by iOS Reference count Xamarin.iOS Peer object UIKit.UIButton Managed memory Allocated by X.iOS Collected by GC IntPtr Handle Peer objects
  • 28. Get to know our enemy: Xamarin iOS Peer objects Native iOS [[UIButton alloc] init] [b release] [b release] Xamarin.iOS var b = new UIButton(…); b = null; b.Dispose(); Release in finalizer, using IntPtr
  • 29. Get to know our enemy: Xamarin iOS Framework peers User peers Peer objects
  • 30. Get to know our enemy: Xamarin iOS Framework peers • Built-in types around iOS objects • Stateless è call native objects to get or set values è Lots of optimizations by the framework • Created first time C# code accesses the object • Can be created on the fly • …
  • 31. Get to know our enemy: Xamarin iOS User peers • Custom type deriving from Framework peer • Have state! public class MyCustomView : UIKit.UIView { public string Text { get; set; } }
  • 32. Get to know our enemy: Xamarin iOS User peers • Have state! èiOS doesn’t know about this additional state èNeeds to be kept alive on managed side
  • 33. Get to know our enemy: Xamarin iOS User peers • Have state! View.AddSubview(new MyCustomView() { Text = "Hello Techorama" }); … if (View.Subviews.Last() is MyCustomView mcv) Debug.WriteLine(mcv.Text);
  • 34. Get to know our enemy: Xamarin iOS User peers - State • Xamarin.iOS ROOTS User peer objects that have no managed references MyCustomView UIView
  • 35. Get to know our enemy: Xamarin iOS User peers - State • Xamarin.iOS ROOTS User peer objects that have no managed references MyCustomView UIView GC Handle
  • 36. Get to know our enemy: Xamarin iOS User peers - State • GC will look at the retain count of native object • Retain Count > 1 è Object is alive and kicking • Retain Count == 1 && no references to managed object è Managed object can be collected
  • 37. Get to know our enemy: Xamarin iOS User peers - State Strong references added by the framework, outside our code, can easily create a reference cycle that can NOT be broken by the GC!
  • 38. Get to know our enemy: Xamarin iOS User peers - Reference cycle GalleryImageView UIView GC Handle GalleryViewController UIViewController Retain count = 2 Retain count = 2 Managed reference View.AddSubview(new GalleryImageView(this));
  • 39. Get to know our enemy: Xamarin iOS User peers - Reference cycle When we navigate back, we get this: GalleryImageView UIView GC Handle GalleryViewController UIViewController Retain count = 1 Retain count = 2
  • 40. Get to know our enemy: Xamarin iOS User peers - Reference cycle When we navigate back, we get this: GalleryImageView UIView GC Handle GalleryViewController UIViewController Retain count = 1 Retain count = 2 Managed reference is still here!!
  • 41. Get to know our enemy: Xamarin iOS User peers - Reference cycle We need to break the cycle when navigating back: GalleryImageView UIView GC Handle GalleryViewController UIViewController Retain count = 1 Retain count = 1 _galleryViewController = null; Retain count = 2
  • 42. Get to know our enemy: Xamarin iOS Peer promotion Framework peer being promoted to User peer _galleryButton = new UIButton(); … _galleryButton.TouchUpInside += GalleryButton_TouchUpInside; è Adding state è Reference cycles!
  • 43. Get to know our enemy: Xamarin iOS Peer promotion Unsubscribe from events (or use storyboard actions) public override void ViewDidAppear(bool animated) { EvilButton.TouchUpInside += EvilButton_TouchUpInside; } public override void ViewDidDisappear(bool animated) { EvilButton.TouchUpInside -= EvilButton_TouchUpInside; }
  • 45. Xamarin iOS Battleplan è Unsubscribe from delegates and events! Except for events/actions set via Storyboard è Call Dispose() on big peers when needed (instead of waiting for GC) è Manually break reference cycles
  • 47.
  • 49. Get to know our enemy: Xamarin Android
  • 50. Get to know our enemy: Xamarin Android How does Android manages memory? GC
  • 51. Get to know our enemy: Xamarin Android Garbage Collectors Both GCs need to work together
  • 52. Get to know our enemy: Xamarin Android Remember Peer objects ?
  • 53. Get to know our enemy: Xamarin Android Peer objects Native Android / Java Native object Java.Lang.Object JVM memory Allocated by JVM Collected by Android GC Xamarin.Android Peer object IJavaObject Managed memory Allocated by X.Droid Collected by GC IntPtr Handle JNI Handle Treated as GC root by JVM
  • 54. Get to know our enemy: Xamarin Android Garbage Collection ‘Normal’ managed objects è ‘Classic’ GC Peer Objects è JNI Handle replaced with Weak Handle è Force Android / Java GC è Weak reference != Alive? è Collect
  • 55. Get to know our enemy: Xamarin Android Garbage Collection Good and bad news… The good: No reference cycle problems as in iOS The bad: GC takes longer & higher memory pressure
  • 56. Get to know our enemy: Xamarin Android Watch out for bitmaps Typically large objects, but not on the Mono-side è Possible no Mono GC will occur è Android GC can’t collect due to active JNI handle
  • 57. Get to know our enemy: Xamarin Android Boxing ArrayAdapter is a Framework peer, using java.util.ArrayList internally, holding references to Java objects è C# objects are boxed to create Java representation
  • 59. Xamarin Android Battleplan è Improve GC performance • Dispose peer objects & set references to null • Periodically trigger a GC è Watch out for Bitmaps, use Dispose/using è Avoid using ArrayAdapter, use BaseAdapter instead è Experiment with ‘new’ GC Bridges
  • 60. Xamarin Android Battleplan GC Bridge Integration between Xamarin GC & JVM GC JVM Mono
  • 61. Xamarin Android Battleplan GC Bridge Default: ‘Old’ bridge Alternatives: ‘New’ and ’Tarjan’ Newer implementations != silver bullet è Experimental, but might work for you è Try it out and test!
  • 63.
  • 65. Get to know our enemy: Xamarin Forms
  • 66. Get to know our enemy: Xamarin Forms Can be both easiest and hardest enemy! General .NET pitfall we already know: Delegates and events Xamarin Forms, ‘knows’ about previous platform-specific pitfalls and takes them into account. BUT all iOS & Droid specific caveats are relevant on effects and renderers!
  • 68.