DEV Community

Young
Young

Posted on

My first blog here, Simply talking about javascript memory relative things.

Care about the basic memory logic in javascript help you write stable code later. Cultivate good habits helps a lot for a beginner

(If this article has any problems, please point out, thanks!!)

At the begin, Let we talk about javascript gc(garbage collection) ways.

As we know, basically there are two normal implementation of gc.

  • Reference counting
    • The object will be recycled in gc statement when it's reference counting equals to 0.
    • Why not use it? Consider about the snippets of code below, both obj1 and obj2 have one reference counting when leave Leak() body, these two objects' memory will not be released forever.
    • Tips rust use reference counting with smart pointer - WeakRef to solve these. Which can be seen in js as well.
function Leak() {
    const a = {} // obj1
    const b = {} // obj2
    b.a = a
    a.b = b
}
Leak()
Enter fullscreen mode Exit fullscreen mode
  • Mark-Sweep

    • Every gc time, javascript engine will mark every object reachable, then watch whole heap, mark unreachable object as unreachable and remove them at the end.
    • From the brief introduction, you can see a huge process of gc which may lead to slowness.
  • V8 garbage collection

    • Talk later.

But in some scenarios, objects will not be recycled forever. We need to pay attention to it.

  • Closure

    • What is closure. A function which is able to access to a function context's variable.
    • Closure will never be recycled.
  • Restore reference to removed dom element

  • Always use global env variable.

  • console

    • Yeah, do not use console in production mode, because console will restrict engine to recycle objects which is logged.

Top comments (0)