SlideShare a Scribd company logo
1 of 55
1© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved.© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved.© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved.
Understanding memory
management in Xamarin Forms
About me
Tsvyatko Konov
@tsvyatco
Agenda
 Forms overview and scenarios
 CG in nutshell
 CG in Mono.NET – nursery, major, tracking
 Mono CG and Java CG
• Tracking
• Cases to watch out – minor can be evil
 Mono CG and IOS refcounting – framework and user pears
• Tracking
• Cases to watch out – object cycles
 Ways to identify memory leaks
Overview of Xamarin Forms
.NET STANDARD
Core library
INFRASTRUCTURE
Xamarin Forms
Mono class libraryBase class
library
Forms scenarios
 When building pure XF app we are shielded from the native platform
• We need to care mainly for memory in the managed word
• Most general .NET practices apply here
 When should we care about Xamarin internals
• Effects
• Custom (and Fast) Renderers
• Native control embedding
• Any time our app crashes with OutOfMemoryException
GC overview
GC overview
 GC help us due to its many benefits
1 Simple to work with
2 Reduces memory Leaks
3 Deals with memory reallocation under the hood
GC - new object allocation
 GC triggers on the current thread when there is not enough space
to satisfy new memory request
A B C
Current pointer
of free space
var D = new D();
GC - new object allocation
 GC triggers on the current thread when there is not enough space
to satisfy new memory request
A B C D
Current pointer of free
space
var D = new D();
GC - reclaiming memory
 GC triggers on the current thread when there is not enough space
to satisfy new memory request
A B C D
E
Current pointer
of free space
var E = new E();
GC overview - traverse
 During collection, GC locates the roots and traverses the live
reference graph
A
B
C
D
Current thread
GC overview – what is root
 Static property
 Reference on the stack of a managed thread
 Objects passed into the native platform and pinned*
GC – reclaiming memory
 GC removes the dead objects and eventually moves rest to
reduce fragmentation and to open space for new objects
A B C D
var E = new E();
GC – reclaiming memory
 GC removes the dead objects and eventually moves rest to
reduce fragmentation and to open space for new objects
A B D
var E = new E();
GC – reclaiming memory
 GC removes the dead objects and eventually moves rest to
reduce fragmentation and to open space for new objects
A B D
var E = new E();
GC – reclaiming memory
 GC removes the dead objects and eventually moves rest to
reduce fragmentation and to open space for new objects
A B D E
var E = new E();
GC in Mono
GC overview
 Mono uses GC similar to .NET one - SGen
• Some differences
– Partial API implementation
– Less generations
GC in Mono
 Offers partial implementation
• Collect
 Missing implementation or exceptions
• AddMemoryPressure
• RemoveMemoryPressure
• WaitForFullGCApproach
• WaitForFullGCComplete
• CancelFullGCNotification
• RegisterForFullGCNotification
Mono Generations
 Nursery
• Tend to hold primarily transient or temporary objects – return values,
strings, temp objects from methods
 Major
• Object that have survived collection – static or long live objects
Mono Generations
D E F G
HNursery
A C
Major
Mono Generations
E G
H
Nursery
A C
Major
Pause Time
 Each time the GC runs the app pauses
 The duration (pause time) it takes to do a collection depends on
• Type or generation of collection
• The size of the live graph
 Our target would be to minimize pause time and the numbers of
major GC
GC in Mono – how to track it
 Xamarin.Android – automatically in debug mode
 Xamarin.IOS – requires environment variables
• MONO_LOG_LEVEL
• MONO_LOG_MASK
25© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved.© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved.© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved.
Demo – tracking GC
Objects in Xamarin
 Some objects live in both the managed and the native world and
must be treated properly to ensure that they are freed from both
worlds.
Xamarin
Managed
Android.Graphics.
Image
IOS/Android
Native
class [UIButton]
Class
android.Graphics.
Image
UIKit.UIButtonBinding layer
Mono GC and Android GC
Xamarin.Android objects
 When using native objects Mono holds a strong reference (root)
to the object (peer) in native heap
public interface IJavaObject : IDisposable
{
IntPtr Handle { get; }
}
Mono
Managed
IJavaObject
JVM
Native
Java Object
Handle
(GC Root in Android)
Mono GC an Android GC
Mono
Managed
IJavaObject
JVM
Native
Java Object
Handle
(GC Root in Android)
Candidate for collection
Mono GCAndroid GC
Mono GC an Android GC
Mono
Managed
IJavaObject
JVM
Native
Java Object
WeakReference
Candidate for collection
Mono GCAndroid GC
Force native GC
Mono GC an Android GC
Mono
Managed
IJavaObject
WeakReference
Mono GCAndroid GC
IsAlive - NO
Mono GC an Android GC
Mono
Managed
IJavaObject
JVM
Native
Java Object
Handle
(GC Root in Android)
Mono GCAndroid GC
IsAlive YES
Pros/Cons
 Pros
• Resolves cyclical references automatically
 Cons
• More memory pressure
• Time consuming GC
Android Peers - samples
 Properties of peers
• Caches
• Additional functionality
 Overridden methods/Properties
Tips
 Reduce the graph of objects living in both worlds, especially the
short lived ones. (wrap or remove them).
 Avoid passing non-peer into Java (as peers are created)
 Since Mono is orchestrating the peer objects, consider calling
GC.Collect when you finish using small C# object that holds big
Java one
Mono
Managed
ImageDrawable
JVM
Native
ImageDrawable
Handle
(GC Root in Android)
~20 b> 1000 kb
36© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved.© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved.© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved.
Demo – peer objects
Mono GC and IOS
IOS – retain count
 IOS uses ARC
A
B
A A A
CB C
RC = 1 RC = 2 RC = 1 RC = 0
Peer objects
 Similar to Android, however increase the RC of a native object
instead
Mono
Managed
INativeObject
iOS
Native
iOS Object
Handle
(RC + 1)
public interface INativeObject
{
IntPtr Handle { get; }
}
IOS + Mono – framework peers
 All ios objects live as framework peers in mono.
Mono
Managed
UIKit.UIButton
iOS
Native
[UIButton]
Handle
(RC + 1)
PeerNative
IOS + Mono – framework peers
 All ios objects live as framework peers in mono.
• Built-in
• Stateless
• Created each time we create or access native object
• No Guaranteed that will keep one peer instance for the same native object
 RC is decremented if peer is disposed or finalized
IOS + Mono – User peers
 Also called derived objects
Mono
UIKit.UIButton
iOS
[UIButton] Handle
(RC + 1)
Mono
MyButton
IOS + Mono – User peers (2)
 Holds managed state (iOS does not know about them)
public class MyButton : UIButton
{
string IconPath { get; set; }
}
IOS + Mono – User peers + GC
 Holding managed reference to User Peer creates reference
cycles that cannot be broken automatically by GC
Mono
MyParentView
iOS
[UIView] Handle
(RC + 1)
Mono
MyButton
iOS
[UIButton]
(RC + 1)
Handle
(RC + 1)
Parent property
IOS + Mono – User peers + GC
 We need to manually break the cycle
Mono
MyParentView
iOS
[UIView] Handle
(RC + 1)
Mono
MyButton
iOS
[UIButton]
(RC + 1)
Handle
(RC + 1)
Parent property
Parent=null;
Dispose()
Promoting User peers
 Adding a state (e.g. event handler) promote framework peer to
user peer.
• We need to manually detach from the event
• Use WeakEventListener
IOS + Mono – User peers + GC
 Xamarin.IOS keeps user peers alive to preserve state
public class CustomRenderer: EntryRenderer
{
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if(disposing && this.Control!=null)
{
this.Control.TouchDown -= OnTouchDown;
this.Control.Dispose();
}
}
}
Techniques for memory tracking
Memory Tracking tools
 VS profiler
 Android monitor
 Apple instruments
 Xamarin profiler
50© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved.© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved.© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved.
Demo - profiler
Memory Tracking – alternatives
 Weak references (native and Mono)
 Finalizers
 Do make sure the code is only executed in Debug
52© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved.© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved.© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved.
Demo
UI for Xamarin
 Leave dealing with these native problems to us while focusing on
your app
 Save time and effort with ready to go toolkit
 Covering various scenarios – 20+ components
• Grid
• Chart
• ListView
• Calendar
• DataForm
• TabView
UI for Xamarin
 Visit our booth in the expo area
Understanding memory management in xamarin forms

More Related Content

Similar to Understanding memory management in xamarin forms

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
 
Xamarin.android memory management gotchas
Xamarin.android memory management gotchasXamarin.android memory management gotchas
Xamarin.android memory management gotchasAlec Tucker
 
Cross platform mobile development in c#
Cross platform mobile development in c#Cross platform mobile development in c#
Cross platform mobile development in c#danhermes
 
Building a full-stack app with Golang and Google Cloud Platform in one week
Building a full-stack app with Golang and Google Cloud Platform in one weekBuilding a full-stack app with Golang and Google Cloud Platform in one week
Building a full-stack app with Golang and Google Cloud Platform in one weekDr. Felix Raab
 
What’s new in aNdroid [Google I/O Extended Bangkok 2016]
What’s new in aNdroid [Google I/O Extended Bangkok 2016]What’s new in aNdroid [Google I/O Extended Bangkok 2016]
What’s new in aNdroid [Google I/O Extended Bangkok 2016]Sittiphol Phanvilai
 
Ignacy Kowalczyk
Ignacy KowalczykIgnacy Kowalczyk
Ignacy KowalczykCodeFest
 
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
 
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)JiandSon
 
Improving app performance with Kotlin Coroutines
Improving app performance with Kotlin CoroutinesImproving app performance with Kotlin Coroutines
Improving app performance with Kotlin CoroutinesHassan Abid
 
End to End .NET Development on Mac
End to End .NET Development on MacEnd to End .NET Development on Mac
End to End .NET Development on MacMike James
 
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
 
dotMemory 4 - What's inside?
dotMemory 4 - What's inside?dotMemory 4 - What's inside?
dotMemory 4 - What's inside?Maarten Balliauw
 
Helping the Lions Roar
Helping the Lions RoarHelping the Lions Roar
Helping the Lions RoarStuart Lodge
 
Cross Platform Development with Xamarin
Cross Platform Development with XamarinCross Platform Development with Xamarin
Cross Platform Development with Xamarinbryan costanich
 
Building native Android applications with Mirah and Pindah
Building native Android applications with Mirah and PindahBuilding native Android applications with Mirah and Pindah
Building native Android applications with Mirah and PindahNick Plante
 
Visual Studio 2017 Launch Event
Visual Studio 2017 Launch EventVisual Studio 2017 Launch Event
Visual Studio 2017 Launch EventJames Montemagno
 
CommunityOneEast 09 - Dynamic Languages: the next big thing for the JVM or an...
CommunityOneEast 09 - Dynamic Languages: the next big thing for the JVM or an...CommunityOneEast 09 - Dynamic Languages: the next big thing for the JVM or an...
CommunityOneEast 09 - Dynamic Languages: the next big thing for the JVM or an...Chris Richardson
 

Similar to Understanding memory management in xamarin forms (20)

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)
 
Xamarin.android memory management gotchas
Xamarin.android memory management gotchasXamarin.android memory management gotchas
Xamarin.android memory management gotchas
 
Cross platform mobile development in c#
Cross platform mobile development in c#Cross platform mobile development in c#
Cross platform mobile development in c#
 
Building a full-stack app with Golang and Google Cloud Platform in one week
Building a full-stack app with Golang and Google Cloud Platform in one weekBuilding a full-stack app with Golang and Google Cloud Platform in one week
Building a full-stack app with Golang and Google Cloud Platform in one week
 
What’s new in aNdroid [Google I/O Extended Bangkok 2016]
What’s new in aNdroid [Google I/O Extended Bangkok 2016]What’s new in aNdroid [Google I/O Extended Bangkok 2016]
What’s new in aNdroid [Google I/O Extended Bangkok 2016]
 
Ignacy Kowalczyk
Ignacy KowalczykIgnacy Kowalczyk
Ignacy Kowalczyk
 
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
 
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
 
Improving app performance with Kotlin Coroutines
Improving app performance with Kotlin CoroutinesImproving app performance with Kotlin Coroutines
Improving app performance with Kotlin Coroutines
 
End to End .NET Development on Mac
End to End .NET Development on MacEnd to End .NET Development on Mac
End to End .NET Development on Mac
 
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...)
 
dotMemory 4 - What's inside?
dotMemory 4 - What's inside?dotMemory 4 - What's inside?
dotMemory 4 - What's inside?
 
Intro to appcelerator
Intro to appceleratorIntro to appcelerator
Intro to appcelerator
 
Helping the Lions Roar
Helping the Lions RoarHelping the Lions Roar
Helping the Lions Roar
 
Cross Platform Development with Xamarin
Cross Platform Development with XamarinCross Platform Development with Xamarin
Cross Platform Development with Xamarin
 
Building native Android applications with Mirah and Pindah
Building native Android applications with Mirah and PindahBuilding native Android applications with Mirah and Pindah
Building native Android applications with Mirah and Pindah
 
Visual Studio 2017 Launch Event
Visual Studio 2017 Launch EventVisual Studio 2017 Launch Event
Visual Studio 2017 Launch Event
 
CommunityOneEast 09 - Dynamic Languages: the next big thing for the JVM or an...
CommunityOneEast 09 - Dynamic Languages: the next big thing for the JVM or an...CommunityOneEast 09 - Dynamic Languages: the next big thing for the JVM or an...
CommunityOneEast 09 - Dynamic Languages: the next big thing for the JVM or an...
 
Understanding meteor
Understanding meteorUnderstanding meteor
Understanding meteor
 
Xamarin v.Now
Xamarin v.NowXamarin v.Now
Xamarin v.Now
 

Recently uploaded

Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutionsmonugehlot87
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 

Recently uploaded (20)

Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutions
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 

Understanding memory management in xamarin forms

  • 1. 1© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved.© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved.© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved. Understanding memory management in Xamarin Forms
  • 3. Agenda  Forms overview and scenarios  CG in nutshell  CG in Mono.NET – nursery, major, tracking  Mono CG and Java CG • Tracking • Cases to watch out – minor can be evil  Mono CG and IOS refcounting – framework and user pears • Tracking • Cases to watch out – object cycles  Ways to identify memory leaks
  • 4. Overview of Xamarin Forms .NET STANDARD Core library INFRASTRUCTURE Xamarin Forms Mono class libraryBase class library
  • 5. Forms scenarios  When building pure XF app we are shielded from the native platform • We need to care mainly for memory in the managed word • Most general .NET practices apply here  When should we care about Xamarin internals • Effects • Custom (and Fast) Renderers • Native control embedding • Any time our app crashes with OutOfMemoryException
  • 7. GC overview  GC help us due to its many benefits 1 Simple to work with 2 Reduces memory Leaks 3 Deals with memory reallocation under the hood
  • 8. GC - new object allocation  GC triggers on the current thread when there is not enough space to satisfy new memory request A B C Current pointer of free space var D = new D();
  • 9. GC - new object allocation  GC triggers on the current thread when there is not enough space to satisfy new memory request A B C D Current pointer of free space var D = new D();
  • 10. GC - reclaiming memory  GC triggers on the current thread when there is not enough space to satisfy new memory request A B C D E Current pointer of free space var E = new E();
  • 11. GC overview - traverse  During collection, GC locates the roots and traverses the live reference graph A B C D Current thread
  • 12. GC overview – what is root  Static property  Reference on the stack of a managed thread  Objects passed into the native platform and pinned*
  • 13. GC – reclaiming memory  GC removes the dead objects and eventually moves rest to reduce fragmentation and to open space for new objects A B C D var E = new E();
  • 14. GC – reclaiming memory  GC removes the dead objects and eventually moves rest to reduce fragmentation and to open space for new objects A B D var E = new E();
  • 15. GC – reclaiming memory  GC removes the dead objects and eventually moves rest to reduce fragmentation and to open space for new objects A B D var E = new E();
  • 16. GC – reclaiming memory  GC removes the dead objects and eventually moves rest to reduce fragmentation and to open space for new objects A B D E var E = new E();
  • 18. GC overview  Mono uses GC similar to .NET one - SGen • Some differences – Partial API implementation – Less generations
  • 19. GC in Mono  Offers partial implementation • Collect  Missing implementation or exceptions • AddMemoryPressure • RemoveMemoryPressure • WaitForFullGCApproach • WaitForFullGCComplete • CancelFullGCNotification • RegisterForFullGCNotification
  • 20. Mono Generations  Nursery • Tend to hold primarily transient or temporary objects – return values, strings, temp objects from methods  Major • Object that have survived collection – static or long live objects
  • 21. Mono Generations D E F G HNursery A C Major
  • 23. Pause Time  Each time the GC runs the app pauses  The duration (pause time) it takes to do a collection depends on • Type or generation of collection • The size of the live graph  Our target would be to minimize pause time and the numbers of major GC
  • 24. GC in Mono – how to track it  Xamarin.Android – automatically in debug mode  Xamarin.IOS – requires environment variables • MONO_LOG_LEVEL • MONO_LOG_MASK
  • 25. 25© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved.© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved.© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved. Demo – tracking GC
  • 26. Objects in Xamarin  Some objects live in both the managed and the native world and must be treated properly to ensure that they are freed from both worlds. Xamarin Managed Android.Graphics. Image IOS/Android Native class [UIButton] Class android.Graphics. Image UIKit.UIButtonBinding layer
  • 27. Mono GC and Android GC
  • 28. Xamarin.Android objects  When using native objects Mono holds a strong reference (root) to the object (peer) in native heap public interface IJavaObject : IDisposable { IntPtr Handle { get; } } Mono Managed IJavaObject JVM Native Java Object Handle (GC Root in Android)
  • 29. Mono GC an Android GC Mono Managed IJavaObject JVM Native Java Object Handle (GC Root in Android) Candidate for collection Mono GCAndroid GC
  • 30. Mono GC an Android GC Mono Managed IJavaObject JVM Native Java Object WeakReference Candidate for collection Mono GCAndroid GC Force native GC
  • 31. Mono GC an Android GC Mono Managed IJavaObject WeakReference Mono GCAndroid GC IsAlive - NO
  • 32. Mono GC an Android GC Mono Managed IJavaObject JVM Native Java Object Handle (GC Root in Android) Mono GCAndroid GC IsAlive YES
  • 33. Pros/Cons  Pros • Resolves cyclical references automatically  Cons • More memory pressure • Time consuming GC
  • 34. Android Peers - samples  Properties of peers • Caches • Additional functionality  Overridden methods/Properties
  • 35. Tips  Reduce the graph of objects living in both worlds, especially the short lived ones. (wrap or remove them).  Avoid passing non-peer into Java (as peers are created)  Since Mono is orchestrating the peer objects, consider calling GC.Collect when you finish using small C# object that holds big Java one Mono Managed ImageDrawable JVM Native ImageDrawable Handle (GC Root in Android) ~20 b> 1000 kb
  • 36. 36© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved.© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved.© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved. Demo – peer objects
  • 37. Mono GC and IOS
  • 38. IOS – retain count  IOS uses ARC A B A A A CB C RC = 1 RC = 2 RC = 1 RC = 0
  • 39. Peer objects  Similar to Android, however increase the RC of a native object instead Mono Managed INativeObject iOS Native iOS Object Handle (RC + 1) public interface INativeObject { IntPtr Handle { get; } }
  • 40. IOS + Mono – framework peers  All ios objects live as framework peers in mono. Mono Managed UIKit.UIButton iOS Native [UIButton] Handle (RC + 1) PeerNative
  • 41. IOS + Mono – framework peers  All ios objects live as framework peers in mono. • Built-in • Stateless • Created each time we create or access native object • No Guaranteed that will keep one peer instance for the same native object  RC is decremented if peer is disposed or finalized
  • 42. IOS + Mono – User peers  Also called derived objects Mono UIKit.UIButton iOS [UIButton] Handle (RC + 1) Mono MyButton
  • 43. IOS + Mono – User peers (2)  Holds managed state (iOS does not know about them) public class MyButton : UIButton { string IconPath { get; set; } }
  • 44. IOS + Mono – User peers + GC  Holding managed reference to User Peer creates reference cycles that cannot be broken automatically by GC Mono MyParentView iOS [UIView] Handle (RC + 1) Mono MyButton iOS [UIButton] (RC + 1) Handle (RC + 1) Parent property
  • 45. IOS + Mono – User peers + GC  We need to manually break the cycle Mono MyParentView iOS [UIView] Handle (RC + 1) Mono MyButton iOS [UIButton] (RC + 1) Handle (RC + 1) Parent property Parent=null; Dispose()
  • 46. Promoting User peers  Adding a state (e.g. event handler) promote framework peer to user peer. • We need to manually detach from the event • Use WeakEventListener
  • 47. IOS + Mono – User peers + GC  Xamarin.IOS keeps user peers alive to preserve state public class CustomRenderer: EntryRenderer { protected override void Dispose(bool disposing) { base.Dispose(disposing); if(disposing && this.Control!=null) { this.Control.TouchDown -= OnTouchDown; this.Control.Dispose(); } } }
  • 49. Memory Tracking tools  VS profiler  Android monitor  Apple instruments  Xamarin profiler
  • 50. 50© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved.© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved.© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved. Demo - profiler
  • 51. Memory Tracking – alternatives  Weak references (native and Mono)  Finalizers  Do make sure the code is only executed in Debug
  • 52. 52© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved.© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved.© 2017 Progress Software Corporation and/or its subsidiaries or affiliates. All rights reserved. Demo
  • 53. UI for Xamarin  Leave dealing with these native problems to us while focusing on your app  Save time and effort with ready to go toolkit  Covering various scenarios – 20+ components • Grid • Chart • ListView • Calendar • DataForm • TabView
  • 54. UI for Xamarin  Visit our booth in the expo area

Editor's Notes

  1. If you check the comments you will also find caps lock disclaimers to not implement this interface 
  2. art] Explicit concurrent mark sweep GC freed 1267(76KB) AllocSpace objects, 0(0B) LOS objects, 18% free, 18MB/22MB, paused 931us total 15.759ms[art] WaitForGcToComplete blocked for 16.412ms for cause Background[Mono] GC_TAR_BRIDGE bridges 186 objects 3717 opaque 1674 colors 200 colors-bridged 176 colors-visible 176 xref 47 cache-hit 0 cache-semihit 0 cache-miss 24 setup 0.03ms tarjan 0.74ms scc-setup 1.50ms gather-xref 0.04ms xref-setup 0.02ms cleanup 0.05ms[Mono] GC_BRIDGE: Complete, was running for 26.40ms[Mono] GC_MINOR: (Nursery full) time 16.62ms, stw 20.24ms promoted 721K major size: 1616K in use: 959K los size: 1024K in use: 138K
  3. -
  4. -