2

Consider JavaScript code below. I am creating array of let's say 4 elements and then immediately delete reference to it. When will garbage collection happen? I know it is specific to language implementation, but we have not that many JavaScript engines.

Edit: it is the simplest possible case, but it interests me because garbage collection causes audible glitches in some web audio applications.

var a = [1, 2, 3, 4];
a = null;
// other code

Update: Javascript and Garbage collection does not explain the sequence of events and how it is triggered. I don't want to control garbage collection. I need better understanding to design better code.

Community
  • 1
  • 1
Ruslanas Balčiūnas
  • 7,310
  • 3
  • 24
  • 41

2 Answers2

1

It's a good approach to delete the references of objects that are no longer in use. Many (almost all) javascript engines use Mark and Sweep approach. If you are deleting a reference to an object and it has no other references, it will probably be collected in the next Mark and Sweep Cycle.

Garbage collection is a cyclic approach that happens in regular intervals in few engines. Some engines say they do GC in an efficient manner but, there are no valid documentation available.

1

There are many ways GCs can be triggered

  • allocation-triggering: there is no more room in the allocation buffers/young generation/howeveritiscalled and a GC is required to free up objects
    This gets a bit more complicated in a mixed GC/manual allocation environment. malloc wrappers might need to trigger GCs too since javascript can hold onto manually allocated resources.
  • [in browsers] when a tab/window gets closed/replaced on the assumption that there is lots of easy-to-collect garbage at that point
  • time-triggered by heuristics for incremental collections to meet pause time goals
  • privileged javascript may be able to trigger collections directly
  • as last-ditch effort by various non-GC-managed components if they run out of native resources (file handles, virtual address space) in the hope that GC objects awaiting finalization were holding onto them

There probably are other reasons that I currently can think of. It's generally not something you should concern yourself with.

If you want to keep GCs low you need to keep your object allocation rate low. E.g. some algorithms can benefit from pre-allocated buffers on which they perform their work. The effectiveness of that strategy depends on whether the javascript runtime has escape analysis and how effective it is at avoiding short-lived allocations in the first place. And on whether the collector is generational. A generational collector suffers a lot less from rapid, short-lived allocations.

the8472
  • 40,999
  • 5
  • 70
  • 122