Lazy load your stuff to decrease your Xamarin mobile app’s memory footprint

Reading Time: 2 minutes

Lazy Loading Kitten?Since memory management is fierce on mobile devices (especially iOS devices) all the lazy loading you can implement will give your app a better memory footprint.
Although Xamarin.iOS / Mono has quite a good Garbage Collection level (either SGen or Boehm) every Image that isn’t needed beforehand will only take up memory if defined on a global scale (like in the AppDelegate, as propery in some sort of container class, etc…)

So how would you feel lazy loading all the about variables, images, even class instances (objects) that you might eventually use, but not upfront?

This is easily implemented using the Lazy<T> class that is available from .Net 4.5 and up!

What Lazy<T> actually does is react on when it is first called and call the constructor of the T defined between angle brackets. So if you have a class named MyClass and it has a public MyClass () constructor the following would initiate lazy load:

As soon as the myClassObject is used somewhere, the Lazy class will initiate the MyClass’s constructor and get your object into the myClassObject variable.
The same goes for images and alike:

And best of all: these simple instantiator functions are all thread safe! Now ain’t that something?!

Now how would you even take more advantage of this? Create a static class and add all these images and other GUI stuff into lazy variables and you can have a Theme like class that contains your entire GUI smuck. For that I won’t take the credit, check out how the guys at Xamarin made an excellent example of this in their prebuilt app called Fieldservice on Github

And if you want to do lazy loading for your ViewModels so they’ll only use memory when the view is used, check out their implementation of a service container in this GitHub File!

Boo-ya that’s awesome!