Under what circumstances does the use of closures in node applications really cause memory leaks?

almost all variables in node are local variables. If closures are used in node, will they be recycled by gc? under what circumstances will the memory of closures not be reclaimed and released by gc? I didn"t pay much attention to writing code before. Online projects restart the application by setting memory thresholds.

like this example

let fn = function () {
  let a = 1
  return function () {
      return a
  }
//  a=null
}
let t=fn()
console.log(t())

at()agc?

Jan.28,2022

closures generally do not cause memory leaks, but it is important to note that
1. Do not make circular references in closures, which can cause serious memory leaks.
2. With regard to the timer called in the function, it needs to be cleared in time when it is not in use.
3. Try not to use global variables to define references to closures, because global variables are only recycled when the page is refreshed [unless cleared manually];
4. To avoid memory leaks in closures, it is best to assign the variable referenced by the function to null [pointing to null] when it is not being used, so that the memory will be reclaimed;


if it is not possible to access t later, you can release a (not without access, but not without access)

{
let fn = function () {
  let a = 1
  return function () {
      return a
  }
//  a=null
}
let t=fn()
console.log(t())
}
console.log(typeof t);//tjsa

No, the purpose of using closures is to prevent it from being recycled.


in your example, t, if it's in another function, then it's done. If it's global scope, it's not a problem of variable visibility.

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b3bd88-41309.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b3bd88-41309.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?