본문 바로가기
개발 언어/자바스크립트 33가지 개념

[JavaScript 33가지 개념] 01. V8 JavaScript engine (Call Stack, Memory Heap)

by 우주다람쥐 2021. 5. 10.
반응형

자바스크립트를 사용하기 위해서는 자바스크립트 엔진이 필요하다.

해당 글에서는 자바스크립트 엔진 중 가장 인기 있는 V8 JavaScript engine이 어떻게 동작하는지 알아볼 것이다.

 

V8 JavaScript engine

What is V8? V8 is Google’s open source high-performance JavaScript and WebAssembly engine, written in C++. It is used in Chrome and in Node.js, among others. It implements ECMAScript and WebAssembly, and runs on Windows 7 or later, macOS 10.12+, and Linu

v8.dev

 

1. V8 JavaScript engine

V8은 C++로 작성된 Google의 오픈 소스이고, 고성능 JavaScript 및 WebAssembly 엔진이다.

Node.js, Google Chrome 등에서 사용하고 있다.

 

V8 엔진에는 두 가지 주요 구성 요소가 있다.

  • Call Stack  우리가 프로그램에서 어디에 있는지 기록하는 함수 호출에 사용되는 LIFO 데이터 구조이다.
  • Memory Heap 은 변수와 개체의 메모리 할당에 사용되는 구조화되지 않은 메모리이다.

 

2. Call Stack (호출 스택)

JavaScript는 단일 스레드 프로그래밍 언어이다.

즉, 한 번에 하나의 작업을 수행할 수 있으며 하나의 호출 스택이 있다.

함수를 호출하면 호출 스택의 맨 위에 푸시되고 함수가 반환되면 호출 스택의 맨 위에서 POP 된다.

기본 예시는 위와 같다.

Call Stack에 순서대로 쌓이고, LIFO 순서대로 실행되는 것을 알 수 있다.

그리고 여기서 호출 스택의 각 항목을 스택 프레임 이라고 한다.

 

만약에 Call Stack에 담을 수 있는 명령어 개수를 초과하면 어떻게 될까?

무한 재귀함수를 만들게 되어서 테스트해보면, Call Stack 허용치를 넘는 순간 다음과 같은 에러를 발생하게 된다.

 

2. Memory Heap

객체와 같은 JavaScript 참조 데이터 유형이 할당되는 곳이다.

스택(call stack)과 달리 메모리 할당은 LIFO 정책 없이 무작위로 배치된다.

또한 힙의 메모리 "구멍"을 방지하기 위해 JS 엔진에는 메모리 관리자가 있어 이러한 문제가 발생하지 않도록 한다.

 

class Animal {}

// 메모리 주소 0x001232에 `new Animal ()` 인스턴스를 저장한다. 
// tiger는 스택의 값으로 0x001232를 가진다. 
const tiger = new Animal ()

// 메모리 주소 0x000001에 `new Object ()` 인스턴스를 저장한다. 
//`lion`은 스택의 값으로 0x000001을 가진다. 
let lion = { 
  strength : "Very Strong" 
}

 

여기서 lion과 tiger는 참조 유형이며, 해당 값은 힙에 저장되고 스택으로 푸시된다.

스택의 값은 힙에있는 위치의 메모리 주소를 보유한다.

 

 

참고 자료

- dev.to/bipinrajbhar/how-javascript-works-under-the-hood-an-overview-of-javascript-engine-heap-and-call-stack-1j5o

 

How JavaScript Works: An Overview of JavaScript Engine, Heap, and Call Stack

Hello everyone 👋, I hope you are doing great. So, today you are going to learn An Overview of JavaSc...

dev.to

- blog.sessionstack.com/how-does-javascript-actually-work-part-1-b0bacc073cf

 

How JavaScript works: an overview of the engine, the runtime, and the call stack

As JavaScript is getting more and more popular, teams are leveraging its support on many levels in their stack - front-end, back-end…

blog.sessionstack.com

- blog.bitsrc.io/memory-leaks-in-nodejs-54ac7bbd4173

 

Understanding Memory Leaks in Nodejs

Understanding JavaScript’s memory model

blog.bitsrc.io

 

반응형

댓글