자바스크립트는 개발자가 메모리를 직접 관리할 수 없다.
내부적으로 Mark-and-Sweep 방법을 사용하여 참조가 없어진 데이터를 알아서 가비지 컬렉팅을 하는 것이다.
그렇다면 참조형 데이터가 참조를 잃었을 때 GC로 메모리가 해제되는 건 알았다.
그렇다면 기본형 데이터는 GC가 일어나는 걸까?
스택오버플로우에서 같은 문제에 대해서 생각해본 사람이 있었고, 어느정도 답변을 얻을 수 있었다.
생각해보니, 당연히 GC는 일어나지 않는다고 보는게 맞는 것 같다.
자바스크립트는 실행 컨택스트 내부에 실행 환경과 관련된 환경이 제공되고, 기본형 데이터는 실행 콘텍스트 (콜스택에 기본형 데이터가 저장된다는 부분이 이 점을 의미하는 것 같다 반면에 참조형 데이터는 힙에 저장된다)에 위치하게 된다.
따라서, 해당 실행 컨텍스트가 필요한 코드의 실행이 끝나면 컨텍스트는 콜스택에서 pop되고, 자연스럽게 해당 변수는 메모리에서 사라지게 된다.
참고 자료 : https://stackoverflow.com/questions/57609678/are-javascript-primitive-types-garbage-collected
Are JavaScript primitive types garbage collected?
I know that in Java and C# the garbage collector is for only reference types (not for primitive types) and works only for heap because objects in Java and C# are stored in the heap. What about
stackoverflow.com
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_management
Memory management - JavaScript | MDN
Low-level languages like C, have manual memory management primitives such as malloc() and free(). In contrast, JavaScript automatically allocates memory when objects are created and frees it when they are not used anymore (garbage collection). This automat
developer.mozilla.org
잘못된 내용이 있다면, 댓글로 알려주시길 바랍니다 😊
'JavaScript' 카테고리의 다른 글
commander.js를 사용한 js CLI 라이브러리 구현 (with 예제) (0) | 2024.06.04 |
---|---|
브라우저 window.navigation 객체로 히스토리 관리하기 (0) | 2024.04.07 |
Web animations API 사용하기 (animate) (0) | 2023.12.11 |
사이트에서 나가시겠습니까? 묻기 (1) | 2023.11.12 |
try catch의 함정 (0) | 2023.11.05 |