1

I'm new to mobile development, and by extension, Xamarin. One thing I've always noticed is that any time a page is loaded, people always request to make a new page() as opposed to have a pool or set list of pages they can access.

Won't this cause memory problems? Does Xamarin automatically remove older pages from the scope? Sorry if it sounds like a dumb question, but it's something that threw me off as my first instinct as a programmer is usually to limit unnecessary repeats of data in the memory.

Amittai Shapira
  • 3,749
  • 1
  • 30
  • 54
TRMN8R
  • 33
  • 5
  • 1
    Could you provide a code sample to illustrate your question? – Bondolin Jul 23 '19 at 17:39
  • 1
    Xamarin apps will AFAIK execute using Mono which provides garbage collection. On today’s hardware, even on mobile platforms, this is probably good enough for things like UI elements which don’t get allocated that often - a page loads after a user gesture, and user gestures happen in geological time as far as a CPU is concerned. As I understand you only need something like object pooling in a GCed runtime in performance-critical and/or memory-constrained scenarios like say games. – millimoose Jul 23 '19 at 17:53

2 Answers2

2

Xamarin is .NET based technology and as such memory management is based on the garbage collection. As such if you follow good practices your generated page that is not needed anymore should be garbage collected at some point.

Ivan Ičin
  • 9,672
  • 5
  • 36
  • 57
1

This is a good question. If you are having a memory leak on the page navigation, you can look at this document first.

The NavigationPage class provides a hierarchical navigation experience where the user is able to navigate through pages, forwards and backwards, as desired. The class implements navigation as a last-in, first-out (LIFO) stack of Page objects.

So you can see that all the pages are on the stack when you are navigating the page. Simply put, xamarin handles their memory release internally as the stack is pushed.

If you are still concerned about memory leaks, you can refer to Xamarin.Forms App Lifecycle to manually release objects based on the end of the page's life cycle.

About Explicit call to garbage collector on navigation back in the stack

This one is a controversial one. Some people say that you should never explicitely call to garbage collector. And, in general, I would agree with this. However, in Xamarin the magic call to GC.Collect() can do wanders. If nothing else helps, just call to GC.Collect(); immidiately after calling await _navigation.PopAsync(true) .

Junior Jiang
  • 12,430
  • 1
  • 10
  • 30