Profiling memory leaks in Xamarin Forms

I remember one time I was working with a mobile project and it was already deployed to the client. It work out well from planning, development, testing to deployment but after a while the client was clamoring that the app is getting slower and slower when it was continuously being used up to the point where it will just crash suddenly. Well it is a given fact maybe not all but I’m guilty of it that we really love our code, so in that sense I was pointing the blame on maybe the device or something unusual that the client was doing with the Application. To make the long story short I’ve learned that Profilers are programmer’s best friend.

cell-phone-690192_640

Introduction

In today’s article I would like to discuss on how to Profile your Xamarin Applications specifically detecting Memory leaks. Later on this article I will show to you the step by step process on how to use  the Xamarin Profiler in detecting the memory leaks. For the sample mobile application you can download the application (link below) and can follow along.

wheelie-bin-2270582_640.jpg

Hello Garbage Collection

We all know that in the .NET world we have a very good friend called Garbage Collector. Basically it is responsible on freeing up the used memory. As simple as it sounds, whether you are in a Desktop, Web or especially mobile where there are two worlds one is Managed and the other one is the native part which at times Garbage Collection is not enough to reclaim those used memories. Remember the story that I told you in the beginning it may not be a shocker now but the cause of the slow down is due to Memory Leaks.

water-pipe-880975_640

What are Memory Leaks?

Memory leaks in the mobile world is a result of incorrect memory management wherein an object is stored in memory but cannot be accessed by the running code. Here are some scenarios but not limited to wherein memory leaks are most likely to happen:

  • Using of Events, delegates or Messaging Centers
  • Using of Images (refer to the famous bitmap example)
  • Creation of custom controls
  • Static Objects or Classes
  • Use of threads

Memory leaks can be very hard to track down using only your instincts or experience so it is a good practice every now an then to perform profiling in your mobile application. In this way as early as development stage you can already detect as well as apply fixes for Memory leak problems.

password-704252_640.jpg

Profilers to the rescue

Profiling is an important and always taken for granted step in development (I’m guilty of it). Based on Xamarin, profiling is under dynamic program analysis wherein simple terms it analyzes your application while it is running or being used.

Profilers are the tools that performs data mining in your application about the usage of particular method, execution time and the memory being allocated. It can help developers to dig deep and analyze the mined metrics to pinpoint the problem or improvement areas in your application.

Always remember that as mobile developers it is crucial that our codes must always be optimized because performance (app fluidity, response time) is much more noticeable on mobile platforms compared to desktop computers.

XamarinProfilerScreenshot.png

Xamarin Profiler

Xamarin Profiler is a great tool created by Microsoft wherein it gives developers ways
to profile or collect telemetry with your Mobile Applications using Visual Studio.
The main function of the profiler is to collect and displays information about the Mobile App wherein the Developer can pinpoint, analyze and optimize areas in their application for a smooth experience by end users. There are different ways the Xamarin Profiler can help us like statistical sampling and Memory profiling. Later will have a go on the Memory profiling using our demo Application. The only caveat that I can think of is that Xamarin Profiler is currently available in Enterprise edition only.

SampleMemoryLeakApp.png

Demo Application

For our demo application will be using Xamarin Forms Android version where in it will be composed of four pages, we have the Main Page and 3 sub pages. The application is simple enough that we will only navigate on different pages then back to the Main page. The only thing is that those sub pages are currently subscribing to the MainPage in order for the Sub pages label will be Updated. If you can browse the code you will quickly see that we are expecting a memory leak in the form of Messaging Center due to the subpages are not unsubscribing.

Using Xamarin Profiler

Let’s open the Demo Project and in order to start your profiling go to tools and click the Xamarin Profiler as seen in figure 1.

Profiler1.PNG
Figure 1. Xamarin Profiler under Tools Tab

You can select on the specific device you want to deploy on or you can also use the built in Emulator as shown in Figure 2.

SelectDevice.PNG
Figure 2. Device Selection

Select the available tools you want to use as shown in Figure 3. In this demo we are going to use the Allocations wherein it mainly concerns the Memory allocations of your application. You can take snapshots and analyze the different objects.

SelectTools.PNG
Figure 3. Select Tools

Once you have selected a Allocations tool you can also configure some options of how the memory profiling will proceed. You can either customize the frames, frequency or either select from the presets as shown in Figure 4.

LevelOfDetail.PNG
Figure 4. Presets for Allocation configuration.

Once you have clicked the Start Profiling button it will automatically launch your selected application on the selected device and you will be greeted with this window as shown in Figure 5.

MainProfiler.PNG
Figure 5. Xamarin Profiler Main Window

There are so many tools or data that the Xamarin Profiler is showing so I will discuss a quick run through on the different parts or categories based on their usage.

  • Brown Area – Represents the Selected device and the Application that is currently running.
  • Green Area – Represents the actual graph of the Memory consumption with respect to time.
  • Red Area – Represents the different data categorized on your selected tab.
  • Orange Area – Represents the information (Object name, count, size) displayed based on the selected tab.
  • Yellow Area –  Represent the real time display of information based on the current snapshot.

Let’s now try to capture two snapshots of the Demo application by capturing snapshot 0 upon start of the application then lets navigate back and forth from main page to other pages and capture our Snapshot 1 as shown in figure 6.

twosnapshots.PNG
Figure 6. Comparing snapshots

One main thing to point out is that both of the Snapshot increased memory consumption but let’s dig deeper on Snapshot 1 and check the effects of the memory leak brought by the messaging center. Just double click the Snapshot 1 at will open a more detail window of the different objects in the snapshot as shown in figure 7.

MemoryLeakDetail.PNG
Figure 7. Snapshot details.

At first glance you will be overwhelmed on the number of objects you can see, but one thing that I am doing is that I’m filtering it to only live objects plus to your namespace only for easy tracking. For this demo we already know that the messaging center is the cause of the leak so will just filter the MessagingCenter as shown in Figure 8.

ActualMemoryleak.png
Figure 8. Filtering of Objects.

Based on the number of objects that has been created on the Subscription it is correct which is 10 because I navigated back and forth 10 times between Main page and sub pages. Now that we have the benchmark to perform the fix let’s modify the code by adding the unsubscribe code on the OnDisappearing method as shown in Figure 9.

OnDisappearing.png
Figure 9. Unsubsribe from the Messaging Center.

Let’s try to profile again our application to see if there is no Memory Leak due to the Messaging Center. So it’s still the same process, but important thing is to rebuild the project deploy it again then after successful deploying in the device that’s the time you start the profiler. Capture a snapshot upon loading of the application then try to navigate 10 times again back and forth then capture again a snapshot of the memory as shown in Figure 10.

AlreadyFixed1
Figure 10. Fixed Messaging Center

As you can see after we applied the fix there is no living object under Messaging Center which is a good thing. Well the consumed memory was low in this demo but imagine the impact that it will bring to an Enterprise grade application.

Here is the URL for the Sample Application: https://github.com/KirkPatrickJunsay/MemoryLeakDemo

Conclusion

To wrap things up, we discussed Profiling our Xamarin Applications focusing on Memory Leaks. We also have an actual demo on the step by step procedure on running Xamarin Profiler. Let me state that Profilers are not only for memory leaks but also can be used in code optimization. Finally moving forward maybe you can also adapt or put in your development routine the profiling of your mobile applications. You can also check other cool Xamarin blogs on the URL below as we continue to celebrate Xamarin’s Month for the whole month of February. A big kudos also for Luis Matos for organizing the Xamarin’s Month.

Here is the URL for Xamarin’s Month Blog Posts: https://luismts.com/blog/xamarin/xamarin-month-february-2019/

Happy Coding 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s