Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic 2 / Ionic 3 - Garbage Collection

I'm trying to get a better understanding of ionic2 and ionic3.

How does the Garbage Collection work in ionic?

  • What gets cached and when?
  • How can we clear this cache?
  • How do we set up elements for G.C.?
  • Do we even need to setup elements for G.C?
  • Can we/Do we need to setup pages for G.C.?

Like seen in this picture (source):

enter image description here

Some of the memory gets G.C'd when going to a new page. However the memory is still significantly higher than before any video had been played.

like image 597
Ivar Reukers Avatar asked Sep 15 '17 11:09

Ivar Reukers


1 Answers

OK I'm gonna give this one a try:

  • Ionic itself has not much to do with GC, there are no scheduled runs of a task that cleans up behind you. The only thing ionic (or more specifically the dev team behind ionic) has to do is to design and implement their UI components in way they do not eat up too much memory and also realease unused memory. Especially with Virtual-Scroll there have been issues with memory-leaks and so on.
  • So lets go a level deeper: Angular! Same point as with ionic. The devs of Angular are responsible for how much memory is used by their framework. But Angular provides a very useful method ngOnDestroy(). Why is this method important to you as an app developer? Because it gives you the chance to clean up behind yourself. This method is called just before your component is destroyed, what does that mean? You do not need your allocated objects, arrays, video-elements (set src='' and then call load()), etc. anymore and you can release the memory. This and this are good reads on how to free memory. However as the docs for onDestory() mention you only have to release memory that is not cleaned up by the automic GC (subscriptions, media-elements, ...). Which brings us to the next level:
  • Javascript/Browser: This is where the "real" GC happens. Javascript uses a mark-and-sweep garbage collecotor (all modern browsers ship with one), you can read about it here. It runs every now and then and releases every object that is unreachable/not referenced anymore, to explicitly mark an object for GC use the delete keyword. The following image visualizes the mark and sweep process:

Javascript mark and sweep algorithm

Image taken from this article, it explains how javascript memory management works in very great detail, I strongly recommend reading it.

  • And of course you always have the native GC of Java/Obj-C which cleans up the native part of the app.
like image 59
David Avatar answered Nov 04 '22 09:11

David