티스토리 뷰

4.3 Garbage collection

Reachability

javascript 메모리 관리의 주된 개념은 접근성이다. 아래는 접근성을 기준으로 메모리에서 삭제될 수 없는 기본적인 대상들이 있다.

  • 현재 실행 중인 함수나 그 함수의 변수 및 파라미터
  • 현재 중첩된 호출의 다른 함수나 그 함수의 변수 및 파라미터
  • 전역 변수
  • 등등 다른 내부적인 것들

위 대상들을 루트라고 부른다.

 

만약 전역 변수에서 어떤 객체를 할당받고, 이후 참조가 변경된다면, (null로 변경하는 등) 메모리는 해당 객체를 정리한다.

// user has a reference to the object
let user = {
  name: "John"
};

user = null; // 참조가 끊어지면서, {name: "John"} 객체는 가비지 컬렉션 대상이 됨.

또한, 두개 이상의 변수에서 참조할 때는, 더 이상 참조하지 않는 변수가 존재할 때까지 garbage collector가 해당 객체를 수거해가지 않는다. 

// user has a reference to the object
let user = {
  name: "John"
};

let admin = user;

user = null; // 원래 객체와의 참조가 끊어졌지만, admin에서 여전히 해당 객체를 참조 중이기에 garbage가 아님.

interlinked objects

서로 연결된 객체들을 예시로 봤을 때, 아래와 같다. 특히, 기억해야 할 만한 것은 메모리 관리 측면에서 나가는 참조는 고려대상이 아니다. 들어오는 참조를 기준으로 접근 여부가 결정되기 때문에, 들어오는 참조가 없는 객체는 제거된다. 

function marry(man, woman) {
  woman.husband = man;
  man.wife = woman;

  return {
    father: man,
    mother: woman
  }
}

let family = marry({
  name: "John"
}, {
  name: "Ann"
});


delete family.father;
delete family.mother.husband;

 

 

또한, 서로 연결되어 있는 객체더라도, 루트로부터 접근가능한지 여부에 따라 제거될 수도 있다.

 

 

Internal algorithms

  • 가비지 컬렉터가 루트부터 모든 참조를 순회하면서 표시(기억)해둔다.
  • 한번 표시한 객체는 두번 방문하지 않으면서 모든 객체를 확인할 때까지 반복한다. 
  • 이후 표시되지 않은 객체는 제거한다.

또 다른 방식의 가비지 컬렉터 알고리즘들...

  • Generational collection – objects are split into two sets: “new ones” and “old ones”. In typical code, many objects have a short life span: they appear, do their job and die fast, so it makes sense to track new objects and clear the memory from them if that’s the case. Those that survive for long enough, become “old” and are examined less often.
  • Incremental collection – if there are many objects, and we try to walk and mark the whole object set at once, it may take some time and introduce visible delays in the execution. So the engine splits the whole set of existing objects into multiple parts. And then clear these parts one after another. There are many small garbage collections instead of a total one. That requires some extra bookkeeping between them to track changes, but we get many tiny delays instead of a big one.
  • Idle-time collection – the garbage collector tries to run only while the CPU is idle, to reduce the possible effect on the execution.
댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday