Clearing items that are no longer referenced and never added to the document

Suppose I create a new element:

let canvas = document.createElement('canvas');

Now, later in the script, I remove any JS references to it.

canvas = null;

Can a creature canvas exist using memory? Or will it be garbage collection, like any other object without links? Please note that I have not actually added it to the document.

+4
source share
4 answers

Is the element <canvas>in itself taking memory? Or will it be garbage collection, like any other object without links?

Yes, it still exists. Yes, it will be garbage collection in due time.

Other posters seem a bit confused by the difference in GC behavior between variable canvas and element <canvas> . , . , . . .

, , . GC'd, . <canvas> , , , null - , (), .

, , , , . , , ( ) , " ", , - . - DOM JS - - GC'd , . :

function a() {
  const div = document.createElement('div');
  return function() {
    console.log(div);
  };
}

function b() {
  const func = a();
}

b func. a, DOM . div , . DOM . b , func , , . , div . , GC'd ( ).

. , .

+4

, , , . , IE.

MDN:

Internet Explorer 6 7, , DOM

:

2012 , . JavaScript (/// ) - , " ".

Mark-and-Sweep , . , , canvas, . , . , let, , , .

+2

Okey, , . document.createElement('canvas').

DOM, , , . null , , .

, . null, .

+1

Take Heap Shot, Record Allocation Time, Record Allocation Profile Profiles DevTools, .

.

  • , JavaScript?
  • DOM

    ( DOM, CSS) JavaScript. - DOM, .

    DOM , . - #tree GC?

      var select = document.querySelector;
      var treeRef = select("#tree");
      var leafRef = select("#leaf");
      var body = select("body");
    
      body.removeChild(treeRef);
    
      //#tree can't be GC yet due to treeRef
      treeRef = null;
    
      //#tree can't be GC yet due to indirect
      //reference from leafRef
    
      leafRef = null;
      //#NOW can be #tree GC
    

    #leaf (parentNode) #tree, leafRef , WHOLE #tree GC.

  • Memory management

If there are no other references to canvas, this should be garbage collection. You can verify this by setting a snapshot.

+1
source

Source: https://habr.com/ru/post/1657535/


All Articles