Cleanup/Destroy Diagram

Hi there,

This might be a really dumb question, but I’ve been unable to location any documentation on how to clean-up a diagram so that the Javascript can garbage collect.

Do I just need to remove the div that the diagram is tied to (and all references in-memory objects) or is there an explicit procedure?

Thanks!

I think that’s correct.

If you don’t want to remove the DIV element and instead want to disassociate the Diagram from the DIV, you can set Diagram.div to null.

If you want to keep both the DIV and the Diagram in place, but want to get rid of all of the contents, you can call Diagram.clear(). This is useful if you want to maintain any DiagramEvent listeners.

The most likely source of accumulating memory is in the UndoManager (when it’s enabled, of course). That’s part of a Model (although it can be shared by multiple models), so another way to “clear out” a diagram, while keeping both the DIV and the Diagram present, is to set Diagram.model to a new, empty model.

Another possible source of garbage retention are the event handlers and listeners, which might retain references to any objects referenced by closed-over variables in closures. As a general policy, unregister any listeners that you register.

2 Likes

Hey @walter! What if i want to remove “div” as well !!

That’s OK too.

How can i do it programmatically in GoJS ?

Just remove the DIV element from the DOM and make sure you don’t keep any references to any GoJS objects: Diagram, Nodes, Links, Model, et al.

Actually it does not clear the memory, it is still preserved in browser

To test this, I took the FlowChart.html sample, removed the lines loading and initializing the GoJS sample framework (which you would not want in your app), and added this test code:

  function reloadMany() {
    myDiagram.div = null;
    myPalette.div = null;
    init();
    setTimeout(reloadMany, 1000);
  }

I took a snapshot of the memory, called reloadMany(), and walked away. When I came back I stopped reloadMany and took another memory snapshot. The memory usage was about the same as it was initially.

Just to be sure, I changed the code to remember the Diagram and Palette instances by pushing them onto an Array held by a global variable. Then the memory usage shot up into the hundreds of MB.

So my guess is that somehow you are retaining a reference to the old Diagram, or to an old Node or Link (which would have a reference to its Diagram).