1

I'm working on some simple script language and I need a help in understanding how garbage collector works. As far as I understand it, garbage collector has two things:

  1. Object pool - contains all allocated objects, can be represented as simple array. When VM creates an object (Number, String and etc) it creates appropriate instance and pushes it into the object pool:

    // init object pool
    var objectPool = [];
    // create new Number
    var numberObj = new Number(123);
    // push numberObj into objectPool
    objectPool.push(numberObj);
    // create new String
    var stringObj = new String("foo");
    // push stringObj into objectPool
    objectPool.push(stringObj);
    
  2. Frame (not sure if it's right term) - contains references to the objects in objectPool. When we create a variable and assign a value to it, VM creates entry in the Frame. When we need to get variable value we look it in the frame. Frame can be represented as hash map:

    // init frame
    var frame = {};
    // create new String
    var stringObj = new String("bar");
    // push stringObj into objectPool
    objectPool.push(stringObj);
    // write stringObj into the frame
    frame["foo"] = stringObj;
    

Garbage collection (at least mark & sweep implementation), contains two steps:

  1. Mark: walk through the objects that is contained in frame and mark them:

    for (var varName in frame)
      frame[varName].marked = true;
    
  2. Sweep: walk through the objects that is contained in objectPool and remove (free) all unmarked ones:

    for (var c = 0; c < objectPool.length; c++) {
      if (!objectPool[c].marked) {
        free(objectPool[c]);
        remove(objectPool[c]);
      }
    }
    

Am I missing anything? Is this all looks correct?

4

0 回答 0