Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unsubscribe subscriptions in component destructor to avoid memory leaks #283

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

Arooba-git
Copy link

Hello 👋
As part of our project, we are using Facebook's new Memlab tool to detect memory leaks in SPA applications and their libraries. While running the tool and analyzing the code of DetektivKollektiv website, we saw that your project does a very good job of ensuring that all async operations are cancelled when components destroy. However, as per Memlab execution results, we found unsubscribed subscriptions causing the memory to leak (screenshots below).

[before]
before subscriptions fix Screen Shot 2023-02-06 at 8 06 13 AM

Hence we added the fix by unsubscribing the subscriptions on component unload, and you can see the heap size and # of leaks reducing noticeably:

after subscriptions fix Screen Shot 2023-02-06 at 7 26 45 PM

Note 1. Host listener is used to ensure that ngOnDestroy is called not only when the class destroy, but also when the page refreshes, tab or browser closes or the user navigates away from the page[1]

Note 2. Static property is used to avoid losing the context of the correct ‘this’ in case any nesting changes are made to the enclosing function in future.

We executed the test suite after the fixes and it successfully passed 65 of 65 total. We also ran the lint on the changes to ensure the added code complies with the lining standard of the project.

You can analyze this and other potential leak sources, if you like, by running Memlab with a scenario file covering the maximum # of use cases.

Following is a sample of the scenario file we used (it needs to be a .js file but attaching here in .txt form):
angular_ui_scenario_memlab.txt

Note that some other reported leaks (in Memlab) originated from Angular's internal objects, and hence were ignored.

References:
[1] https://wesleygrimes.com/angular/2019/03/29/making-upgrades-to-angular-ngondestroy.html

@Arooba-git
Copy link
Author

bump @PotSchmoell

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant