4

We have an application with complex and lengthy view. A view have approximately 50 components with own services, subscriptions, behaviors. Component have own variables including Arrays and FormGroups.

Problem: After navigating back to View1(Component1) from View2(Component2), I still see data of View2(Component2) in chrome devtool in Memory tab, and everytime it increase 25 MB memory in snapshot.

Eg:

  • First time snapshot of View1 --> 50 MB
  • Navigate to View2. Navigate to View1 --> snapshot size is 75 MB
  • Navigate to View2. Navigate to View1 --> snapshot size is 100 MB

Every time, when I navigate to View2, it increases loading time by 4-5 seconds. I am clearing all subscriptions of View2, but still after navigating View1, it is showing me all Arrays and FormGroups, View2 component, variables with data.

I am expecting View1 should have same size after navigating from View2.

I have created small application and result is same,

[![enter image description here][1]][1]

Is this expected behavior or I need to take some steps?

In actual application, I see below snapshot after navigating back to View1. enter image description here

I can see all FormGroups, arrays of previous Views.

Keval Patel
  • 161
  • 1
  • 15

1 Answers1

3

These are the reasons for memory leacking in angular.

  1. Unsubscription of Service(API) call => If you Navigate from one component view to another component view and you didn't unsubscribe first view services by using the onDestroy method it will re-render recursively and it causes a memory leak.

  2. Lazy loading => Nowadays lazy loading is the most important functionality to prevent memory leaking or memory consumption. check lazy loading in angular link

  3. Didn't do code optimization => As a developer, code optimization is the most important point to prevent memory leak to re-use same code or same service in different component/service.

  4. Not Using Redux/Ngxs/Ngrx => Redux is one of the features to reuse the same common data in a project.

    https://www.ngxs.io/getting-started/installation

So, Kindly check these points and apply them to your code structure to prevent memory leaks or if you need any other help please provide extra details of your code structure.

Aniruddh Thakor
  • 1,396
  • 2
  • 9
  • 18
  • Thank you for reply, I am unsubscribing mostly all observers, and I have lazy loading in place too. – Keval Patel Dec 30 '21 at 09:55
  • 1
    Then please check if you are using a method in Html like `*ngIf="getCondition()"` condition that always re-render and it would also cause a memory leak. – Aniruddh Thakor Dec 30 '21 at 10:08