📍 Javascript는 Managed 언어이기 때문에 Allocate와 Release를 알아서 수행한다.
- managed language: 메모리의 할당 및 해제를 위한 메모리 관리 기능을 언어차원에서 담당
- unmanaged language: 개발자가 명시적으로 메모리를 할당하고 해제하기위해 malloc(), free()와 같은 low-level 메모리 제어 기능을 제공
정적 메모리 할당 (static allocation)
동적 메모리 할당 (dynamic allocation)
const developer = {
name: 'Martin',
age: 24
}
const hobbies = ['game', 'reading', 'exercise'];
const age = 24;
const newName = 'Mari';
function getDeveloperName() {
return developer.name;
}
위와 같은 코드가 있다고 가정했을 때, 아래와 같이 메모리에 할당이 된다.
javascript에서는 무언가(객체, 문자열 등)가 생겨날 때 메모리가 할당되며 이들이 더이상 사용되지 않을때는 ‘자동으로' 메모리가 반환되는데, 이러한 과정을 가비지컬렉션(garbage collection) 이라 한다.
function foo(arg) {
bar = 'some text';
// window.bar = 'some text'; 와 동일하다.
// 또는 this.bar = 'some text';
}
var theThing = null
var replaceThing = function () {
var originalThing = theThing
// 상위 스코프인 originalThing을 참조하는 스코프를 갖게됨
// 동시에 theThing 도 참조하게됨.
var unused = function () {
if (originalThing) console.log('hi')
}
//
theThing = {
longStr: new Array(1000000).join('*'),
someMethod: function () {
console.log(someMessage)
},
}
}
setInterval(replaceThing, 1000)
var elements = {
button: document.getElementById('button'),
image: document.getElementById('image')
};
function doStuff() {
elements.image.src = 'http://example.com/image_name.png';
}
function removeImage() {
// image는 body 요소의 바로 아래 자식임
document.body.removeChild(document.getElementById('image'));
// 이 순간까지 #button 전역 요소 객체에 대한 참조가 아직 존재함
// 즉, button 요소는 아직도 메모리 상에 있고 가비지컬렉터가 가져갈 수 없음
}
var serverData = loadData();
setInterval(function() {
var renderer = document.getElementById('renderer');
if(renderer) {
renderer.innerHTML = JSON.stringify(serverData);
}
}, 5000); // 매 5초 마다 실행
const timer = setInterval() => {...}, 5000);
clearInterval(timer);