What is causing the lack of proper and consistent cleanup of nodes and listeners?

I am currently investigating a memory leak related to the nodes count, but I am finding it difficult to understand Angular's behavior. The results are inconsistent and do not provide a clear explanation of what is happening.

I have developed a simple application with 1 controller and 2 views. Both views utilize the same controller:

core.controller('CoreCtrl', [function() {

  var core = this;

  core.helloWorld = function() {
    console.log('hello world');
  };
}]);

core.config(['$routeProvider', function($routeProvider) {
  $routeProvider
    .when('/test1', {
      template: '<a href="#/test2" ng-click="core.helloWorld()">Go to test 2</a>',
      controller: 'CoreCtrl',
      controllerAs: 'core'
    })
    .when('/test2', {
      template: '<a href="#/test1" ng-click="core.helloWorld()">Go to test 1</a>',
      controller: 'CoreCtrl',
      controllerAs: 'core'
    })
    .otherwise({redirectTo: '/test1'});
}]);

I conducted a timeline recording in Chrome dev tools by rapidly switching between views and then alternating every other second, as indicated in the graph.

Here are the results:

https://i.sstatic.net/CYJsf.png

After the initial quick view switching, there is a significant drop in nodes count. Subsequently, when switching views at a slower pace followed by quicker switches, the decrease in nodes count is not as pronounced as before, and the count continues to rise afterward.

There are two key points that concern me:

  • Why does the nodes and listeners count increase after switching views before dropping again? Shouldn't this pattern resemble more of a sawtooth shape, - _ - _ - _ - _-, given that each view switch should clean up nodes and listeners?

  • Why is the second drop in node count not as drastic as the first one?

It seems like there may be an issue with cleaning up resources efficiently during view switches. Or perhaps something is not being cleaned up correctly, despite no manual cleanup required for listeners.

Can anyone provide insight into these test results?

Answer №1

Why does the count of nodes and listeners continue to rise after switching views, only decreasing after a certain period of time? Shouldn't this follow more of a sawtooth pattern, - _ - _ - _ - _- since each view switch should trigger a cleanup of nodes and listeners?

The memory doesn't immediately decrease because garbage collection is not something you can control on demand. Typically, the browser cleans up memory when it needs to free up space for additional allocations.

For debugging purposes, there's a "Collect garbage" button in the DevToolbar (). It's recommended to press this button at the start and end of each recording session, and in your case, even after every page switch. This ensures that you're monitoring used memory rather than just occupied memory.

Why is the second drop in memory not as significant as the first one?

This could be due to the same underlying cause.


I conducted a profiling of your code and observed the timeline after manually initiating garbage collection:

https://i.sstatic.net/wmoWi.png

From the results, it appears that event listeners and nodes were properly cleaned up.

If you are still encountering lag on slower machines despite this cleanup, it could be because these machines exhaust memory quickly and require frequent garbage collection cycles.

As mentioned in the DevTools documentation:

A page’s performance is delayed or appears to pause frequently. This might indicate frequent garbage collections, where the browser reclaims memory. These pauses occur whenever garbage collection is performed. Therefore, if the browser conducts extensive garbage collections, script execution will be frequently paused.

Your app may be grappling with a more complex issue than what is evident from this simple example. Further investigation would be necessary to pinpoint the specific problem affecting your application.

I found the Chrome DevTools CPU throttling feature helpful in replicating the sluggishness experienced by users in my application. Additionally, this talk by the Gmail team elucidates how to identify and resolve issues related to memory usage and app performance.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In JavaScript programming, the function is always executed after the bottom code

I am currently working on a piece of code that is partially functional. The purpose of this code is to verify the existence of an email address in a database. If the email does not exist, it should return true; $(document).ready(function() { var ema ...

the process of triggering animation to start automatically when a button is clicked in Web Development

I'm looking to create a React component that triggers an animation when clicked. I have a few options in mind: If the props are changed in the middle of the animation, it should restart the animation. The props can be changed by clicking a button on ...

Display the preset user coordinates on the map using AngularJS

When a user logs in, I want to display pre-defined coordinates on the map. Here is my map: map.html <!DOCTYPE html> <!-- To change this license header, choose License Headers in Project Properties. To change this template file, choose Tools | Tem ...

What is the right way to choose the default option in a list?

I have 6 lists that I populate via a script. Using AngularJS, my HTML structure is as follows: <div class="advancedSearch hidden"> <div class="col-md-4 col-xs-12"> <select name="number" ng-model="Numbers" ng-change="listSearchC ...

`Shifting a spherical object from point A to point B along its axis`

I am currently working on a project that involves rotating a sphere from point A to point B on itself. After finding Unity3d code for this, I came across the following solution: Quaternion rot = Quaternion.FromToRotation (pointA, pointB); sphere.transform ...

Having trouble implementing a directive in an AngularJS 1.5 component

After upgrading to angular version 1.5.0, I realized that a directive I created could be improved using the new .component() notation. However, the require property no longer functions as expected. Here is a simplified example: angular.module('myA ...

Retrieving a value in the app component from a map using Angular

I have been struggling to display the values of ValueM, ValueR, and product in my app.component.html file. Can anyone offer a solution or tip to help me move forward? Thank you very much. app.component.ts forkJoin( this.service1.method1(filter1), ...

Utilizing React's useState hook triggers the addition of a <canvas> element to the HTML document

I've come across a strange issue involving React's useState. Whenever I try to set the state using it, an unexpected <canvas> element appears in my main <html> structure! import React, { useState } from 'react'; import &apos ...

How is it possible to encounter a Javascript unexpected token ] error within an HTML code?

While working on my project, I encountered a JavaScript error in the console of Chrome. The error message stated "Unexpected token ]" and it was pointing to a specific line of raw HTML code. I am puzzled about what could be causing this issue. Unfortunatel ...

Detect keypress within a BrowserWindow even when multiple BrowserView components are present

In my Electron application, I have a main BrowserWindow that contains the main user interface index.html, along with multiple BrowserView elements: browserWindow = new BrowserWindow({ width: width, height: height, frame: false }); browserWindow.webContents ...

Validate the historical and present contents of a variable

Let's take a look at my code snippet: <button id="submit">Roll</button> <script> function generateRandomNumber(range) { var result = ''; var characters = '123456789'; var c ...

Tips for modifying the content of a div within an HTML document after a certain period of time has elapsed, and then repeating the process

Currently, I am in the process of developing an Android app that will function as a Digital Display. One of the challenges I am facing involves displaying an HTML page with multiple regions or boxes, each containing various items that need to switch dynami ...

Properly Adding an External jQuery File in HTML Using jQuery

Seeking assistance as a newcomer to JS and programming in general. Currently working on a website where each page has its own HTML / PHP file, with jQuery and global JS functions included in the footer via a separate includes file "footer.php". Everything ...

Is there a way to customize the JavaScript click event for specific elements only?

I've been following a tutorial from codrops where each item has a hover event and a click event that triggers an anime.js function. My goal is to prevent certain items (grid cells) from triggering the anime.js function when clicked, while still allow ...

Check out Mongo DB using Mongo compass

I am a beginner with MongoDB and Node. I successfully connected to Mongo as shown below: const mongoose = require("mongoose") mongoose.connect('mongodb://localhost/testaroo', { useNewUrlParser: true }) mongoose.connection.once('open', ...

How can I trigger an onclick event for a link automatically upon loading in Laravel?

I am presenting the link below: <a href="javascript:void(0)" onclick="xtenderSearchItem.modal_visibility = ! xtenderSearchItem.modal_visibility;">Request</a> My goal is for it to change the language of the page (which occu ...

Responsive design in Android does not function as intended

My goal is to create a responsive design for my website, but I am encountering issues with importing the CSS files into the HTML. When I try to view the site in both the Windows version of Chrome and the Android version, all I see is a white screen. I am c ...

When the video message bubble is touched within the chat app, a video player will automatically pop up (using React Native)

Currently, I am developing a chat app in React Native that can handle the sending and receiving of video files. However, I am facing challenges with activating the video player when a user presses on the video message inside the chat bubble. Despite my att ...

What could be causing the row not to delete from the table? Is there something crucial that is overlooked in the JavaScript, HTML, or PHP function?

In my admin interface, I have tables that display various data: questions, replies, and users. Each row in these tables includes a small cancel.png image, meant to serve as a delete button. However, clicking on these buttons does not trigger any action, ev ...

Problem encountered while generating a torus shape using webGL

I am currently developing a program that aims to create 3D parametric shapes using webgl. The current code I have works successfully for rendering a sphere, but when I try switching the equations for a torus, only the upper half of the torus is being displ ...