Garbage collection is failing to release objects stored in the global array

Question regarding memory management in a JavaScript program.

In my code, I have a global array called g_objArr, which is used to store customer profile details. This array contains objects with various customer information fields.

The issue arises when the g_objArr gets reset and reloaded with new data each time a different customer profile is selected using the function loadCustomerDetails(). This constant reloading of large arrays is causing excessive memory usage in my application.

Initially, I tried clearing the array by setting g_objArr.length = 0 to destroy references to previous objects. However, my teammate suggested that instead of manually clearing the array, we should identify and remove any lingering references to objects within it so that the garbage collector can handle it automatically.

Considering the widespread use of g_objArr throughout the codebase, pinpointing these dangling references may be time-consuming. Upon initial examination, I couldn't find any obvious culprits apart from loop iterations.

So, the question remains: Should we rely on the garbage collector to clean up unused object references in the global array, or do we need to explicitly clear it every time? Is there perhaps a memory analysis tool in vscode that could help us address this issue more efficiently?

Thank you for your insights!

Additional note: The application is locally hosted on vscode, not on a web server.

Answer №1

V8

Upon conducting a brief investigation, it has been revealed that vscode is actually an electron application that utilizes both nodejs and the V8 JavaScript engine. If you desire to verify this information, feel free to conduct your own search.

GC

The process of Memory Garbage Collection in JavaScript revolves around determining whether data stored on the heap can be accessed by code, which is slightly different from merely holding references to the data on the heap. Global variables, for example, are undeniably "reachable" and will not undergo garbage collection simply because they are not currently being referenced elsewhere in the code.

The JS engine automatically manages GC, but it can also be manually triggered in node by invoking global.gc. However, this feature needs to be enabled in the node configuration using the --expose-gc flag. It's possible to configure vscode to launch node with additional settings at startup, although I cannot personally confirm this.

Dangling References

If the value of g_objArr is copied in various parts of the code, it could potentially reduce available heap space:

const userData = g_objArr;

This action creates a reference to the array currently held in g_objArr. If g_objArr is updated, then userData becomes the outdated previous value. As long as it remains reachable (such as when executed at file level or within a closure with nested functions that are accessible), it won't be garbage collected until the assignment to userData occurs again. If this process is repeated in multiple locations within code that isn't executed for every user, it could significantly impact available heap space.

Similar considerations apply to retaining references to specific array elements or the outcomes of using Array methods like slice, which generate cloned copies of all or part of a user's data.

If your colleague was hinting at investigating dangling references, it would be wise to explore this further, regardless. As mentioned by @Pointy, proving the existence of a memory leak should consider the fact that the GC may be invoked inconsistently by the JS engine. If the issue lies in the user profile expanding beyond the feasible heap capacity, indicating a design flaw rather than a problem with garbage collection.

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

Close popup after submitting the form

On my website, I have a function to submit a form within a modal. Everything works well except for when I uncomment a certain line of code. When I uncomment that line, my test mysql insert on the page /index.php/trainings/add doesn't get executed. I a ...

Axios sending a 400 Bad Request to Django due to a missing required field

I'm having issues sending a POST request from my React frontend using Axios. import axios from 'axios' axios.post('http://server:port/auth/login', { username: 'admin', password: 'MY_PASSWORD', }, { ...

Validating a string using regular expressions in JavaScript

Input needed: A string that specifies the range of ZIP codes the user intends to use. Examples: If the user wants to use all zip codes from 1000 to 1200: They should enter 1000:1200 If they want to use only ZIP codes 1000 and 1200: They should enter ...

Using HTML5 input type number along with a regular expression pattern

In order to display only numbers and forward slashes in the input field with regex pattern, I attempted the following code: <input type="number" pattern="[0-9\/]*"> However, this code only shows the number pad from 0 to 9. How can I modify the ...

The issue I'm facing with the change handler for the semantic-ui-react checkbox in a React+Typescript project

Hey there! I'm currently facing an issue with two semantic-ui-react checkboxes. Whenever I try to attach change handlers to them, I end up getting a value of 'undefined' when I console log it. My goal is to retrieve the values of both check ...

Tips for maintaining a consistent height for elements in HTML

As the content of td increases, the height of th also increases. How can we ensure a fixed height for th. This is the HTML code: <table id="depts"> <tr> <th>Topic Title</th> <th><a href="create.php?id= ...

Display a webpage containing error messages and user input that can be sent back to the AJAX request

My form collects user information such as name, surname, etc. Here is an example of one input field: <div class="form-group"> <label for="name">Name</label> <input type="text" class="form-control" id="name" name="name" value= ...

Using Express.js to send responses piece by piece

Is it possible to send a response in chunk of data using Express.js? I experimented with this code on an online demo: const express = require('express'); const app = express(); const port = 3111; const sleep = (ms) => { return new Promise(( ...

Leveraging the package.json file to execute a separate script within the package.json file

Within my project's package.json file, I have a script called npm run script1. Additionally, my project includes a private npm package as a dependency, which contains its own set of scripts in its package.json file, including one named script2. My goa ...

Adjust the background color of the dropdown when toggled

I want to add a background color to my dropdown menu when it's activated. In the demo, the dropdown content overlaps with the text behind it. Currently, I have a scrollspy feature that applies a background color to the nav bar and dropdown menu when s ...

Choose elements in jQuery that lack a specific class

How can I efficiently select all elements with the .hi class that do not include the .image class? <div class="hi"> <div class="hue"> <div class="image"> 456 </div> </div> </d ...

What steps should I take to resolve this unexpected issue with svelte?

Whenever I attempt to execute the application, an error is consistently displayed to me. Here is a screenshot of the error: https://i.sstatic.net/jfo3X.png This issue always arises on the initial import type line, regardless of the content or arrangement ...

Apply a specific image layout once the drop event occurs

I have a container with 5 image pieces that need to be dropped into another container to complete the image. Once an image is dropped, I want to apply the style "position:absolute" so that it sticks to the previous image in that container. Although I have ...

Is there a way to implement word wrapping in li text without making any changes to its width

Is there a method to wrap the content inside li elements without modifying their width? As an illustration, consider the following structure - <ul> <li>Text Example</li> <li>Text Example</li> <li>Text Exampl ...

Tips for stopping the entire webpage from scrolling in Vuetify

Hey there, I'm facing an issue with scrolling on mobile devices and iPads. When I view my site on desktop, there is no scrolling behavior, but as soon as I switch to a mobile device or iPad, the scroll appears. This problem is specific to mobile devic ...

Can you tell me why the outputs of these two codes are different when I ran them?

Recently I was tackling a challenge in JavaScript where the task involved dividing the number of volunteers by the number of neighborhoods. To achieve this, I decided to use the array method .length which would return the length of an array. However, what ...

Determine which points fall within a specified radius by utilizing solely an array

I'm developing an application that utilizes Leaflet to store GPS coordinates of specific locations in a table format [lat,lng]. This functionality is only accessible from the back end. On the front end, I need to retrieve the current position and gen ...

In Reactjs, Axios and fetch are both commonly used for sending ongoing network requests to localhost

In order to establish a successful connection between the express backend and MongoDB database, I initially used fetch("/") from the frontend, which returned the index.html code. However, when I switched to fetch("http://localhost:9000"), I encountered a C ...

Showcasing a graphical representation with the help of Highcharts

I am currently exploring JavaScript and trying to familiarize myself with interactive charts using the HighCharts library. Unfortunately, I have been facing some challenges in getting the graph to print correctly. Despite attempting various examples, none ...

Can you explain the distinction between using router.METHOD() versus router.route() in Express?

There are two different ways I've come across of writing this code. router.get(path, callback) and router.route(path).get(callback) Based on the surrounding code, they seem to have the same functionality. The documentation for these methods can be ...