Search code examples
c#xamarinobject-pooling

Why don't people use object pooling in Xamarin?


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.


Solution

  • 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) .