-
[Javascript] 메모리 힙 & 콜 스택프로그래밍 언어/JavaScript 2024. 1. 19. 13:03
힙(heap)과 콜스택(call stack)이란?
자바스크립트 엔진이 코드를 읽고 실행하는 과정에서 중요한 두 단계로 정보를 저장하는 것, 코드를 트래킹하는 작업 두가지가 있다.
이때 정보를 저장하는 공간(메모리)가 메모리 힙이고, 코드를 트래킹하는 영역이 콜스택이다.아래 코드를 통해 콜스택과 힙이 어떤식으로 작동하는지 알아보자
const a = 10 const b = 35 const arr = [] function func() { const c = a + b; // 스코프 체인에 따라 GEC의 VO 참조 obj = { d: c } return obj } const o = func()
1. 먼저 원시 값과 참조 값으로 구분되어서 각각 콜스택과 힙에 위치한다.
2. func() 가 실행되면서 새로운 컨텍스트가 쌓이게 된다.
3. 이후 위에 위치한 컨텍스트부터 아래로 실행되면서 작업을 수행한다.
콜스택
메모리에 존재하는 공간 중 하나로 코드를 읽어내려가면서 수행할 작업들을 쌓고, 작업 수행에 필요한 것들을 힙에서 찾아 작업을 수행하는 공간이다. 원시형 타입의 값과 실행 컨텍스트가 저장된다.
힙
콜스택이 작업 수행에 필요한 값이 저장되며 참조형 데이터 값이 저장된다.
가비지 컬렉터
콜스택과 힙은 한정적인 공간이기에 효율적인 관리를 위해 자바스크립트는 자동으로 메모리를 관리하는 프로세스인 가비지 컬렉터를 통해서 필요가 없어진 데이터를 자동으로 삭제하는데 이를 통해서 필요한 데이터만 메모리 힙에 저장함으로 메모리를 더욱 여유롭게 관리할 수 있다.
🔗 reference
- https://github.com/baeharam/Must-Know-About-Frontend/blob/main/Notes/javascript/stack-heap.md
- https://donguk.netlify.app/javascript/%EB%A9%94%EB%AA%A8%EB%A6%AC-%ED%9E%99-&-%EC%BD%9C-%EC%8A%A4%ED%83%9D/
'프로그래밍 언어 > JavaScript' 카테고리의 다른 글
[Javascript] 이터레이터, 제너레이터 (0) 2024.01.19 [Javascript] prototype, class (0) 2024.01.18 [Javascript] 메모리 할당 (0) 2024.01.18 [Javascript] 즉시 실행 함수 IIFE (0) 2024.01.18 [Javascript] strict mode (0) 2024.01.18