Ionic 2 / Ionic 3 - Garbage Collection - ionic-framework

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

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:
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.

Related

How to fix memory leaks in iOS applications?

I have found few memory leaks when I am running my application. For your reference, I am sharing the screenshots of Instrument debug logs and also Xcode Debugg memory graph tool. I am not getting what is going wrong here. Please help me to resolve memory leaks.
Please help me to fix the memory shows in the image. Thank you.
I know this is an old question, but a few observations.
When you have a lot of objects that are leaking, focus on high level objects (especially your own classes). We do not care why the array was not released. We care about why the item that is keeping a strong reference to it was not released. XTubeManager and GlueTubeManager are probably good places to start searching, but I don't know what other high level objects appear in the panel on the left.
When you have leaks, it is very useful to use the “Malloc Stack Logging” feature. So edit your scheme (command+<; or “Product” » “Scheme” » “Edit”) and go to the “Diagnostics” section and temporarily turn on “Malloc Stack Logging”:
Then, when you select a leaked object, you can see where it was instantiated but using the memory inspector panel on the right:
Look for entries in that stack trace that are white (your code), as opposed to all the system items that are in gray. When you hover items in that stack trace, there is even a little arrow that lets you jump to the code in question. In my example, the leaked object was instantiated in viewDidLoad.
This will not tell you why it leaked, but you will be able to see where the object in question was instantiated in your code, and you can start your investigation from there, diagnosing why an object created at that point in your code still has lingering strong references.
Remember to turn off the “Malloc Stack Logging” feature when you are done with your diagnostics.
As an aside, when we see URLSession objects that were not released, that begs the question of whether you instantiated a URLSession object (rather than using the shared instance) and neglected to call finishTasksAndInvalidate. Ideally, you would have a single URLSession and reuse it for all network activity (or use the shared instance), but if you must instantiate sessions, make sure to invalidate them when you are done.
You do NOT need to use Instruments. That's the old way. Use Xcode itself.
See Visual Debugging with Xcode
- 24:45
Watching the video is a MUST, but the summary of the video is as such:
There are two type of memory problems. You just have to repeat a flow in your app 2-3 times to be certain the memory graph has caught it
Leaks. Xcode will annotate this with purple icon. Possible are: delegates, closures
Abandoned memory. Xcode will not annotate this. But it's still increases your memory footprint. possible examples are: A repeating timer that is never invalidated, NotificationCenter, A never ending DispatchWorkItem
For Leaks the memory graph is a loop ie two way.
For Abandoned memory the graph is NOT two way. It's just an object one that Apple categorizes as 'root path' referencing your object and never letting it go. For more on this see here
In this case, just because some tool says you’ve got a memory leak doesn’t mean you have one. The amount of data seems to be less than 1MB, that’s nothing. Your tool suspects there’s a leak because data was allocated and not released, but these are single objects. Quite possible that memory is going to be released or reused later.
Use your software for hours and check if memory usage gets larger.
Memory on mobile devices is a shared resource. Apps that manage it improperly run out of memory, crash, and suffer from drastically decreased performance.
so to fix it follow this steps
Open Xcode and build for profiling.
Launch Instruments.
Use the app, trying to reproduce as many scenarios and behaviors as possible.
Watch for leaks/memory spikes.
Hunt down the source of the memory leaks.
Fix the problem.

Advantages of Ionic lazy loading

Did a simple Google search:
https://www.google.com/search?q=advantages+of+ionic+lazy+loading
And couldn't really find a detailed description of the advantages of lazy loading. Anyone care to explain?
Long story short: (startup)-performance!
The underlying problem:
When you do a cold start of your app (no resume) the webview engine needs to load, parse and interpret a lot of javascript to become useable. The top high-end devices are mostly capable of doing so in a kind of acceptable timeframe but on hardware which is a few years old or simply not equipped with enough CPU power this may take a while.
Another problem (especially when developing PWAs) is network speed, with WiFi or 4G it is no problem (but also far from ideal!) at all to quickly download a few MBs of javascript. But on a slow 3G connection you can go and drink a coffee while waiting until your app becomes interactive.
Lazy-loading to the rescue!
So how can we minimize the effort to make the app interactive faster? We split up our heavy main bundle into many smaller bundles. So if we start our app now, only the bare minimum of javascript needed for the first page has to be fetched and parsed. Every time we need a specific feature (a page) we do the loading just in time (lazy) instead of ahead of time (eager). By always just fetching a small chunk of javascript when needed the performance gain will be huge for some devices but will definitly noticeable on every device.
If you implement lazy-loading in Ionic3 your code also becomes more modular and maintainable because you will create a self-contained Angular module for every IonicPage and by pushing a string onto the nav-stack instead of an actual page instance you remove a lot of dependencies (imports) in your code.

iPhone Development - Memory limitation for iphone application

Can anyone point into the right direction here. I want to respond when my application receives memory warning, (i want to know how to respond to this notification). Plus, How much memory can i wire with my application?
Any articles or book reference would be great. Thanks.
If your app gets a memory warning (such as in your view controller's didReceiveMemoryWarning method) you need to release any non-critical data. Anything that you're using that cached, for example, or that can be regenerated, should be dumped.
For example, if your app crunches some numbers and stores the result in a big array, if you're not actively using that array, you should release it. Then, regenerate it when you need it again.
A little more information is here:
Observing Low-Memory Warnings
I've heard informally that warnings get issued when your application hits about 22 MB. (Any allocated memory is included -- the iPhone keeps everything in physical RAM and doesn't page out to any other storage.) Given that the phone only has 128 MB of total RAM, this seems plausible.
That limit does not include the memory used by shared system libraries, such as the Objective-C runtime. And while I'm not entirely sure on this, I don't think WebKit's memory usage is included for the UIWebView component, as I believe WebKit is always loaded (but again, not 100% sure on that).
The best thing to do when you hit this limit is free anything that you can easily regenerate or re-read from input files, such as views, images, and cached data.

Best approach to debugging applicationDidReceiveMemoryWarning on iPhone?

Need advice on how to debug this. I'm new with limited environments and have no previous embedded or smart phone programming experience so I could use some clues.
Already aware of:
Instruments, Clanger Static Analysis, manual code review, etc. Instruments seems to be very helpful in general but quite time consuming and freezes up a lot of the time! Clanger has also helped me a lot as well. It seems like I'm just consuming too much memory in general and I'm wondering what a good strategy is. Do I release some top-level objects? Is there a 'preferred strategy'?
Just wondering if anyone has tackled this successfully and if they have any other suggestions? Thanks all.
There are a lot of good articles for memory management in an iPhone app. Here are some useful links.
http://iosdevelopertips.com/objective-c/memory-management.html
http://kosmaczewski.net/2009/01/28/10-iphone-memory-management-tips/
https://cocoa-touch.blogspot.com/2008/09/memory-management-on-iphone.html
Things you should in general take care of
Release any variables which you do not need
Always handle didReceiveMemoryWarning and release any variables not in use
Stop any memory-heavy processes in applicationDidReceiveMemoryWarning like audio/video playing, UIImagePickerController etc
EDIT
This does not apply any more. imageNamed: had caching issues prior to 3.x OS versions. The issue does not exist any more and you should use imageNamed: (makes implementing retina display easier)
Do NOT use imageNamed: to create UIImage objects.
Basically you're receiving this warning because (unsurprisingly) the iPhone is dangerously low on memory. This can generally be for one of two reasons;
You have a memory leak.
You are allocating far too many objects and need to revisit your design.
For the first one you should run instruments and examine your memory allocations. This can really slow down your app (and requires additional memory) so try testing areas of your app one at a time. E.g. if you have multiple views switch between them a couple of times.
For the second you will have to examine things you are doing that could result in large memory allocations. For example if you're writing a Flickr browser you might need to cut down the number of images you have loaded at anyone time, or free up some unused ones when you receive this warning.
These are about the only general rules I can suggest without knowing more about your app.
Unfortunately there's no real way (that I know of) to get figures for current memory allocation from the iPhone OS. This makes it really difficult to isolate the areas of your application that are inadvertently memory hungry.

In CocoaTouch (iPhone OS) how do I find/eliminate leaks that the Instruments Leak tool doesn't find?

I have an iPhone app that is running great in the simulator. It responds well to the memory warnings by getting rid of everything that is not absolutely essential. When I run it on the device, it runs well. But after a certain amount of usage it crashes with error code 101 - which, from what I can tell, is the OS killing it due to memory usage. I can see the memory warning (I'm logging it), and my app responds to it, but dies shortly thereafter.
If I look at the app in Instruments (either on the device or in sim), it doesn't find any leaks. In addition, the net memory usage is in the range of 600-700k bytes. Transitioning from the different views of my app increases memory usage (as expected), but when the views and controllers are released and dealloc'd, the memory usage never quite goes as low as it was. However, the addition is usually only something in the range of 1000-2000 bytes. So while Leaks shows me no leaks, I suspect there is an issue somewhere. I've also looked at all of the objects I'm allocating, and all of them seem to be reclaimed as expected. The only objects I see that keep increasing are GeneralBlock-N (where N is some number)
Should I not pay any attention to Instruments net usage figure? What would be the next steps in trying to diagnose the issue?
ADDED: I'm not making any calls to malloc() or any CoreFoundation libraries that would return a buffer that I'm responsible for. The only non-Obj-C calls I'm making are logging statements to NSLog.
One quick thing to try is running the Clang static analyzer. This will find some, but not all, issues in your code that you might be missing. It checks the code at compile time, so it's by no means infallible, but will almost certainly find most glaring problems.
You should also run your application with the memory monitor instruments to see overall system usage on the device.
Leaks only finds memory that is not referenced by anything, but still retained.
What you are seeing is that you have left memory retained, and still referenced by something.
One thing to look for especially, is that if you have passed a reference of a class to something else as a delegate that you free it in your dealloc method.
Similarly, if you have subscribed to any notifications you should unsubscribe in viewWillDisappear: (if you use the general unsubscription method in a view controller do not forget to re-subscribe to the memory warning notification.
Timers are the same way, deactivate them when a view goes away and re-enable them when the view comes back (unless of course you need a timer running the whole time your application is running).
Basically be suspicious of anything you give a reference of a class to, and try to figure out how you might eliminate that link whenever possible (either in dealloc or viewWillDisappear: or both).
Here's a summary of what I've learned (thanks to some excellent answers and comments):
Object Allocation is NOT the same as Memory usage. The answer to my question about ObjectAlloc's net bytes element is that you shouldn't be paying attention to it - at least not when determining issues with the amount of memory you are using or whats causing it to crash. It doesn't reflect the true memory usage of your application.
My amatuerish guess is that ObjectAlloc only shows you the memory taken up by the direct object itself. So if you have an UIImageView, it takes up just a handful of bytes to store the various properties, but it might be pointing to an image in memory taking up a bunch of space. Therefore, looking at ObjectAlloc is helpful only in making sure you're not creating and keeping objects around, it won't give you an idea of how much memory you're using or how much you can use before crashing.
MemoryMonitor will give you the total memory usage. You can constrain it to viewing only your app's usage by using the search tool in the bottom right of the Instruments window.
Both ObjectAlloc and Memory Monitor (as well as the Leaks tool) are plugins for Instruments - just in case thats not obvious to someone else. You can launch Instruments from within XCode by doing Run -> Start with Performance Tool. Once inside of Instruments, you can open the Library and add new plugins to monitor different aspects of performance.
One thing to look for is circular references.
(I don't want this to sound patronising - just want to make sure I'm being clear:) If object a refers to object b and object b refers to object a, there may not be a reported "leak" because all the memory is still referenced - but this may be an orphaned island of objects, seperated from your app and never reclaimable. Of course it may involve more objects ( a refers to b, b refers to c, c refers to a, etc).
If you're building up a graph of objects somewhere, and there are any back or cross references, be sure to break the circles if you release the root (there are different ways of doing this. The simplest is probably to make sure each class in question has a releaseAll method, or similar - which calls releaseAll on it's child objects, then releases the child objects - but this isn't always the best solution).