Kurs JavaScript i TypeScript · Moduł 10: TypeScript w praktyce
Zarządzanie pamięcią - garbage collection, memory leaks
W tej lekcji6
Wyobraź sobie wybieg, z którego nikt nie wywozi resztek karmy. Przez kilka dni nic nie widać, a po miesiącu T-Rex nie ma gdzie stanąć. Tak działa wyciek pamięci (memory leak): aplikacja trzyma dane, których już nie potrzebuje, i z każdą godziną zwalnia. Zarządzanie pamięcią jest jednym z najważniejszych aspektów wydajności. Mimo że JavaScript ma automatyczny garbage collector, musisz rozumieć, jak działa pamięć, aby unikać wycieków.
Jak działa pamięć w JavaScript
Memory lifecycle
Każda wartość przechodzi trzy etapy: alokację, użycie i zwolnienie. Dwa pierwsze widzisz w kodzie, trzeci wykonuje za Ciebie garbage collector (GC):
// Cykl życia pamięci w JavaScript
const memoryLifecycle = {
// 1. Alokacja pamięci - automatyczna
allocation: () => {
const obj = { name: 'John', age: 30 }; // Alokacja w heap
const arr = [1, 2, 3, 4, 5]; // Alokacja w heap
const num = 42; // Alokacja w stack (primitive)
return { obj, arr, num };
},
// 2. Użycie pamięci - odczyt/zapis
usage: (data) => {
data.obj.name = 'Jane'; // Użycie zaalokowanej pamięci
data.arr.push(6);
console.log(data.obj, data.arr);
},
// 3. Zwalnianie pamięci - automatyczne przez GC
release: () => {
// Gdy zmienne wychodzą poza scope, stają się kandydatami do GC
// GC uruchomi się automatycznie w odpowiednim momencie
}
};
// Demonstracja cyklu
function demonstrateMemoryLifecycle() {
const data = memoryLifecycle.allocation(); // Alokacja
memoryLifecycle.usage(data); // Użycie
// Po zakończeniu funkcji, 'data' staje się kandydatem do GC
}
demonstrateMemoryLifecycle();Nie wywołujesz żadnego free(). Gdy data przestaje być osiągalne po zakończeniu funkcji, obiekt staje się kandydatem do sprzątnięcia, a moment wybierze GC.
Stack vs Heap
Często mówi się, że prymitywy żyją na stosie (stack), a obiekty na stercie (heap):
// Stack - przechowuje prymitywy i referencje
function stackExample() {
const a = 5; // Stack
const b = 'hello'; // Stack (reference do string w heap)
const c = true; // Stack
console.log('Stack variables:', a, b, c);
} // Po zakończeniu funkcji, wszystko ze stack zostaje usunięte
// Heap - przechowuje obiekty i tablice
function heapExample() {
const obj = { x: 1, y: 2 }; // Obiekt w heap, referencja w stack
const arr = [1, 2, 3]; // Tablica w heap, referencja w stack
// Modyfikacja obiektu w heap
obj.z = 3;
arr.push(4);
return { obj, arr }; // Zwracamy referencje
} // Referencje ze stack są usuwane, ale obiekty w heap pozostają
// Memory allocation visualization
class MemoryVisualizer {
constructor() {
this.allocations = [];
this.currentId = 0;
}
allocate(type, size, description) {
const allocation = {
id: this.currentId++,
type: type, // 'stack' | 'heap'
size: size,
description: description,
timestamp: Date.now(),
freed: false
};
this.allocations.push(allocation);
console.log(`Allocated ${type}: ${description} (${size} bytes)`);
return allocation.id;
}
free(id) {
const allocation = this.allocations.find(a => a.id === id);
if (allocation) {
allocation.freed = true;
allocation.freedAt = Date.now();
console.log(`Freed: ${allocation.description}`);
}
}
getMemoryStats() {
const active = this.allocations.filter(a => !a.freed);
const freed = this.allocations.filter(a => a.freed);
return {
totalAllocations: this.allocations.length,
activeAllocations: active.length,
freedAllocations: freed.length,
totalActiveSize: active.reduce((sum, a) => sum + a.size, 0),
memoryLeaks: active.filter(a => Date.now() - a.timestamp > 30000) // > 30s
};
}
}
const memoryViz = new MemoryVisualizer();
// Przykład użycia
function demonstrateMemoryAllocation() {
// Stack allocations
const stackId1 = memoryViz.allocate('stack', 8, 'number variable');
const stackId2 = memoryViz.allocate('stack', 8, 'string reference');
// Heap allocations
const heapId1 = memoryViz.allocate('heap', 64, 'object {name, age, city}');
const heapId2 = memoryViz.allocate('heap', 32, 'array [1,2,3,4,5]');
// Symulacja zwalniania pamięci
setTimeout(() => {
memoryViz.free(stackId1);
memoryViz.free(stackId2);
console.log('Memory stats:', memoryViz.getMemoryStats());
}, 1000);
setTimeout(() => {
memoryViz.free(heapId1);
// heapId2 nie zostaje zwolniony - symulacja memory leak
console.log('Final memory stats:', memoryViz.getMemoryStats());
}, 2000);
}To uproszczony model. Specyfikacja ECMAScript nie określa, gdzie w pamięci leżą wartości, więc decyduje silnik: na przykład napisy i zmienne złapane przez domknięcia trafiają na stertę. MemoryVisualizer tylko symuluje alokacje, ale dobrze pokazuje, czym jest wyciek: wpisem, którego nikt nie zwolni.
Garbage Collection w JavaScript
Typy algorytmów GC
Porównaj dwie strategie. Zliczanie referencji (reference counting) usuwa obiekt, gdy nic na niego nie wskazuje. Mark-and-sweep zaczyna od korzeni (roots), takich jak zmienne globalne i stos wywołań, oznacza wszystko, co da się z nich osiągnąć, a resztę usuwa:
// 1. Reference Counting (stary algorytm)
class ReferenceCountingDemo {
constructor() {
this.objects = new Map();
}
createObject(id, data) {
const obj = {
id: id,
data: data,
refCount: 1,
references: []
};
this.objects.set(id, obj);
console.log(`Created object ${id} with ref count: 1`);
return obj;
}
addReference(fromId, toId) {
const fromObj = this.objects.get(fromId);
const toObj = this.objects.get(toId);
if (fromObj && toObj) {
fromObj.references.push(toId);
toObj.refCount++;
console.log(`Object ${toId} ref count increased to: ${toObj.refCount}`);
}
}
removeReference(fromId, toId) {
const fromObj = this.objects.get(fromId);
const toObj = this.objects.get(toId);
if (fromObj && toObj) {
const index = fromObj.references.indexOf(toId);
if (index > -1) {
fromObj.references.splice(index, 1);
toObj.refCount--;
console.log(`Object ${toId} ref count decreased to: ${toObj.refCount}`);
// Auto GC when ref count reaches 0
if (toObj.refCount === 0) {
this.collectObject(toId);
}
}
}
}
collectObject(id) {
const obj = this.objects.get(id);
if (obj) {
// Recursively decrease reference counts
obj.references.forEach(refId => {
this.removeReference(id, refId);
});
this.objects.delete(id);
console.log(`Collected object ${id}`);
}
}
// Problem: Circular references
createCircularReference() {
const obj1 = this.createObject('circular1', 'First object');
const obj2 = this.createObject('circular2', 'Second object');
// Wzajemne referencje - memory leak w reference counting!
this.addReference('circular1', 'circular2');
this.addReference('circular2', 'circular1');
console.log('Created circular reference - will never be collected!');
return { obj1, obj2 };
}
}
// 2. Mark and Sweep (nowoczesny algorytm)
class MarkAndSweepDemo {
constructor() {
this.objects = new Map();
this.roots = new Set(); // Global variables, stack references
}
createObject(id, data) {
const obj = {
id: id,
data: data,
references: [],
marked: false
};
this.objects.set(id, obj);
return obj;
}
addToRoots(id) {
this.roots.add(id);
console.log(`Added ${id} to GC roots`);
}
removeFromRoots(id) {
this.roots.delete(id);
console.log(`Removed ${id} from GC roots`);
}
addReference(fromId, toId) {
const fromObj = this.objects.get(fromId);
if (fromObj && !fromObj.references.includes(toId)) {
fromObj.references.push(toId);
}
}
// Mark phase - oznacza wszystkie osiągnalne obiekty
markPhase() {
console.log('Starting mark phase...');
// Wyczyść poprzednie oznaczenia
this.objects.forEach(obj => obj.marked = false);
// Oznacz wszystkie obiekty osiągnalne z roots
const visited = new Set();
const markRecursive = (id) => {
if (visited.has(id)) return;
visited.add(id);
const obj = this.objects.get(id);
if (obj) {
obj.marked = true;
console.log(` Marked object ${id}`);
// Rekurencyjnie oznacz referencje
obj.references.forEach(refId => markRecursive(refId));
}
};
// Rozpocznij od wszystkich roots
this.roots.forEach(rootId => markRecursive(rootId));
}
// Sweep phase - usuwa nieoznaczone obiekty
sweepPhase() {
console.log('Starting sweep phase...');
const toDelete = [];
this.objects.forEach((obj, id) => {
if (!obj.marked) {
toDelete.push(id);
}
});
toDelete.forEach(id => {
console.log(`Collecting object ${id}`);
this.objects.delete(id);
});
console.log(`Collected ${toDelete.length} objects`);
}
// Pełny cykl GC
runGarbageCollection() {
console.log('Running garbage collection...');
this.markPhase();
this.sweepPhase();
console.log(`Active objects: ${this.objects.size}`);
}
// Demonstracja rozwiązywania circular references
demonstrateCircularReferences() {
// Tworzenie obiektów z circular references
const obj1 = this.createObject('mark1', 'Object 1');
const obj2 = this.createObject('mark2', 'Object 2');
const obj3 = this.createObject('mark3', 'Object 3');
// Circular references
this.addReference('mark1', 'mark2');
this.addReference('mark2', 'mark3');
this.addReference('mark3', 'mark1'); // Circular!
// Tylko obj1 jest w roots
this.addToRoots('mark1');
console.log('Before GC - objects with circular references');
this.runGarbageCollection(); // Wszystkie będą oznaczone jako osiągalne
// Usuwamy z roots
this.removeFromRoots('mark1');
console.log('After removing from roots');
this.runGarbageCollection(); // Wszystkie będą zebrane mimo circular references!
}
}Dwa obiekty wskazujące na siebie nawzajem oszukają zliczanie referencji, ale nie mark-and-sweep: gdy żaden korzeń do nich nie prowadzi, znikają oba. Dlatego nowoczesne silniki używają mark-and-sweep, a sam cykl referencji nie jest już wyciekiem. Po fazach mark i sweep silnik może jeszcze zagęścić pamięć (compact), żeby usunąć dziury.
Generational Garbage Collection
Większość obiektów żyje krótko, więc silniki dzielą stertę na generacje. Młodą sprzątają często i szybko, a obiekty, które przetrwają kilka cykli, trafiają do starej:
// Nowoczesne silniki JS używają generational GC
class GenerationalGCDemo {
constructor() {
// Różne generacje obiektów
this.youngGeneration = new Map(); // Nowe obiekty
this.oldGeneration = new Map(); // Stare obiekty
this.permanentGeneration = new Map(); // Bardzo stare obiekty
this.gcCycles = 0;
this.promotionThreshold = 3; // Ile cykli GC przeżyć aby zostać promowanym
}
allocateObject(id, data, size = 64) {
const obj = {
id: id,
data: data,
size: size,
generation: 'young',
gcSurvived: 0,
allocatedAt: Date.now(),
lastAccessed: Date.now()
};
this.youngGeneration.set(id, obj);
console.log(`Allocated ${id} in young generation`);
return obj;
}
accessObject(id) {
let obj = this.youngGeneration.get(id) ||
this.oldGeneration.get(id) ||
this.permanentGeneration.get(id);
if (obj) {
obj.lastAccessed = Date.now();
console.log(`Accessed object ${id}`);
}
return obj;
}
// Minor GC - tylko young generation
runMinorGC() {
console.log('Running Minor GC (young generation)...');
this.gcCycles++;
const survivors = [];
const toPromote = [];
this.youngGeneration.forEach((obj, id) => {
// Symulacja: obiekty używane w ostatnich 5 sekundach przeżywają
const timeSinceLastAccess = Date.now() - obj.lastAccessed;
if (timeSinceLastAccess < 5000) {
obj.gcSurvived++;
survivors.push({ id, obj });
// Promocja do old generation
if (obj.gcSurvived >= this.promotionThreshold) {
toPromote.push({ id, obj });
}
console.log(`Object ${id} survived (count: ${obj.gcSurvived})`);
} else {
console.log(`Collected young object ${id}`);
}
});
// Wyczyść young generation
this.youngGeneration.clear();
// Przywróć survivors
survivors.forEach(({ id, obj }) => {
if (!toPromote.find(p => p.id === id)) {
this.youngGeneration.set(id, obj);
}
});
// Promuj do old generation
toPromote.forEach(({ id, obj }) => {
obj.generation = 'old';
this.oldGeneration.set(id, obj);
console.log(`Promoted ${id} to old generation`);
});
console.log(`Minor GC completed. Young: ${this.youngGeneration.size}, Old: ${this.oldGeneration.size}`);
}
// Major GC - wszystkie generacje
runMajorGC() {
console.log('Running Major GC (all generations)...');
const collectFromGeneration = (generation, name) => {
const survivors = new Map();
let collected = 0;
generation.forEach((obj, id) => {
const timeSinceLastAccess = Date.now() - obj.lastAccessed;
// Old generation ma dłuższy czas życia
const threshold = name === 'old' ? 10000 : 5000;
if (timeSinceLastAccess < threshold) {
survivors.set(id, obj);
} else {
collected++;
console.log(`Collected ${name} object ${id}`);
}
});
generation.clear();
survivors.forEach((obj, id) => generation.set(id, obj));
return collected;
};
const youngCollected = collectFromGeneration(this.youngGeneration, 'young');
const oldCollected = collectFromGeneration(this.oldGeneration, 'old');
console.log(`Major GC completed. Collected ${youngCollected + oldCollected} objects`);
console.log(`Remaining - Young: ${this.youngGeneration.size}, Old: ${this.oldGeneration.size}`);
}
// Automatyczny GC na podstawie heurystyk
autoGC() {
const youngSize = this.youngGeneration.size;
const oldSize = this.oldGeneration.size;
// Triggers dla GC
if (youngSize > 100) { // Dużo młodych obiektów
this.runMinorGC();
}
if (oldSize > 50 || this.gcCycles % 10 === 0) { // Dużo starych obiektów lub co 10 cykli
this.runMajorGC();
}
}
getGenerationStats() {
return {
young: this.youngGeneration.size,
old: this.oldGeneration.size,
permanent: this.permanentGeneration.size,
totalGCCycles: this.gcCycles
};
}
}
// Demonstracja generational GC
const genGC = new GenerationalGCDemo();
// Symulacja allocation patterns
function simulateAllocationPattern() {
// Tworzenie wielu krótkotrwałych obiektów
for (let i = 0; i < 50; i++) {
genGC.allocateObject(`temp_${i}`, `Temporary object ${i}`);
}
// Tworzenie kilku długotrwałych obiektów
for (let i = 0; i < 5; i++) {
const longLived = genGC.allocateObject(`long_${i}`, `Long-lived object ${i}`);
// Symulacja regularnego dostępu
setInterval(() => {
genGC.accessObject(`long_${i}`);
}, 1000);
}
// Automatyczny GC co dwie sekundy
setInterval(() => {
genGC.autoGC();
console.log('Generation stats:', genGC.getGenerationStats());
}, 2000);
}Symulacja upraszcza jedno: prawdziwy GC nie sprawdza, kiedy ostatnio użyłeś obiektu, tylko czy jest osiągalny. V8 ma generację młodą i starą, a generacja permanent to pojęcie z dawnej Javy.
Rodzaje Memory Leaks
Zmienne globalne, listenery, timery, domknięcia i DOM
Wyciek to obiekt wciąż osiągalny, choć już go nie potrzebujesz. Oto pięć typowych źródeł wraz z poprawnymi wersjami:
// Problem: Niekontrolowane globalne zmienne
class GlobalVariableLeaks {
static demonstrateLeaks() {
// BAD: Przypadkowe globalne zmienne
// Uwaga: kod w klasie zawsze działa w trybie strict, więc tutaj obie linie rzucą błąd.
// Taki wyciek powstaje w zwykłym skrypcie bez 'use strict'.
function accidentalGlobal() {
// Brak 'var', 'let', 'const' - tworzy globalną zmienną!
leakedVariable = 'This will leak!';
// Też globalnie przez 'this' w non-strict mode
this.anotherLeak = { data: new Array(1000).fill('leak') };
}
accidentalGlobal();
// Te zmienne pozostaną w pamięci do końca działania aplikacji
console.log('Leaked variables:', window.leakedVariable, window.anotherLeak);
}
static demonstrateSolutions() {
// GOOD: Używaj strict mode
'use strict';
function properFunction() {
// ReferenceError zamiast globalnej zmiennej
// notDeclared = 'This will throw error in strict mode';
let properVariable = 'This is properly scoped';
const anotherProper = { data: 'safe' };
return { properVariable, anotherProper };
}
// GOOD: Moduł pattern
const safeModule = (function() {
let privateData = [];
return {
addData: function(item) {
privateData.push(item);
},
getData: function() {
return privateData.slice(); // Return copy
},
clear: function() {
privateData = [];
}
};
})();
return { safeModule };
}
}
// 2. Event Listeners
class EventListenerLeaks {
constructor() {
this.data = new Array(10000).fill('memory consuming data');
this.handlers = new Map();
}
// BAD: Event listeners bez cleanup
addLeakyListeners() {
const button = document.getElementById('leaky-button');
// Problem: listener referencje obiekt, który może mieć dużo danych
const handler = () => {
console.log('Clicked!', this.data.length);
};
button?.addEventListener('click', handler);
// Kiedy komponent jest usuwany, listener pozostaje!
// Cały obiekt nie może być zebrany przez GC
}
// GOOD: Proper cleanup
addProperListeners() {
const button = document.getElementById('proper-button');
const handler = (event) => {
console.log('Proper click!', event.target.id);
};
this.handlers.set('button-click', handler);
button?.addEventListener('click', handler);
}
cleanup() {
// Zawsze usuń event listeners podczas cleanup
this.handlers.forEach((handler, key) => {
if (key === 'button-click') {
const button = document.getElementById('proper-button');
button?.removeEventListener('click', handler);
}
});
this.handlers.clear();
console.log('Event listeners cleaned up');
}
// Modern approach: AbortController
addModernListeners() {
const controller = new AbortController();
const signal = controller.signal;
document.addEventListener('click', (event) => {
console.log('Modern click!', event.target);
}, { signal });
// Cleanup wszystkich listeners na raz
setTimeout(() => {
controller.abort();
console.log('All listeners aborted');
}, 10000);
}
}
// 3. Timers i Intervals
class TimerLeaks {
constructor() {
this.data = new Array(100000).fill('timer data');
this.timers = new Set();
}
// BAD: Timers bez cleanup
createLeakyTimers() {
// Problem: setInterval referencje całą klasę
const intervalId = setInterval(() => {
console.log('Leaky timer tick', this.data.length);
}, 1000);
// Timer nigdy nie zostaje wyczyszczony!
// Obiekt nie może być zebrany przez GC
return intervalId;
}
// GOOD: Tracked timers
createTrackedTimers() {
const intervalId = setInterval(() => {
console.log('Tracked timer tick');
}, 1000);
this.timers.add(intervalId);
// Auto cleanup po czasie
const timeoutId = setTimeout(() => {
this.clearTimer(intervalId);
}, 10000);
this.timers.add(timeoutId);
return intervalId;
}
clearTimer(timerId) {
clearInterval(timerId);
clearTimeout(timerId);
this.timers.delete(timerId);
console.log(`Timer ${timerId} cleared`);
}
cleanup() {
this.timers.forEach(timerId => {
clearInterval(timerId);
clearTimeout(timerId);
});
this.timers.clear();
console.log('All timers cleaned up');
}
// Modern approach: AbortController dla async operations
createAbortableTimer() {
const controller = new AbortController();
const timer = {
start: () => {
const interval = setInterval(() => {
if (controller.signal.aborted) {
clearInterval(interval);
return;
}
console.log('Abortable timer tick');
}, 1000);
return interval;
},
stop: () => {
controller.abort();
}
};
return timer;
}
}
// 4. Closures
class ClosureLeaks {
static demonstrateLeaks() {
function createLeakyClosures() {
const largeData = new Array(1000000).fill('leak data');
// Problem: closure trzyma referencję do całego scope
return {
// Nawet jeśli używamy tylko małej części danych
getSmallPart: function() {
return largeData.slice(0, 10);
},
// Ta funkcja też trzyma całe largeData w pamięci
getLength: function() {
return largeData.length;
}
};
}
const leaky = createLeakyClosures();
console.log('Small part:', leaky.getSmallPart());
// largeData pozostaje w pamięci mimo że potrzebujemy tylko length!
return leaky;
}
static demonstrateSolutions() {
function createOptimizedClosures() {
const largeData = new Array(1000000).fill('optimized data');
// GOOD: Wyciągnij tylko potrzebne dane
const smallPart = largeData.slice(0, 10);
const dataLength = largeData.length;
// largeData może być zebrany przez GC
return {
getSmallPart: function() {
return smallPart;
},
getLength: function() {
return dataLength;
}
};
}
// GOOD: Null references when done
function createCleanClosures() {
let data = new Array(100000).fill('clean data');
const api = {
process: function() {
const result = data.map(item => item.toUpperCase());
data = null; // Explicit cleanup!
return result;
}
};
return api;
}
return { createOptimizedClosures, createCleanClosures };
}
}
// 5. DOM References
class DOMReferenceLeaks {
constructor() {
this.domReferences = new Map();
this.observers = [];
}
// BAD: Holding DOM references
createDOMLeaks() {
// Problem: referencje do usuniętych elementów DOM
const elements = document.querySelectorAll('.dynamic-content');
elements.forEach((element, index) => {
this.domReferences.set(`element_${index}`, {
node: element, // Direct reference!
data: new Array(1000).fill(`data_${index}`)
});
});
// Nawet jeśli elementy zostaną usunięte z DOM,
// pozostaną w pamięci przez te referencje!
}
// GOOD: WeakMap dla DOM references
createSafeDOMReferences() {
const elementData = new WeakMap();
const elements = document.querySelectorAll('.safe-content');
elements.forEach((element, index) => {
// WeakMap pozwala na GC elementu gdy zostanie usunięty z DOM
elementData.set(element, {
id: index,
data: new Array(1000).fill(`safe_data_${index}`)
});
});
return elementData;
}
// Proper cleanup dla DOM observers
setupDOMObserver() {
const observer = new MutationObserver((mutations) => {
mutations.forEach(mutation => {
console.log('DOM changed:', mutation.type);
});
});
observer.observe(document.body, {
childList: true,
subtree: true
});
this.observers.push(observer);
// Auto cleanup
setTimeout(() => {
this.cleanupObservers();
}, 30000);
}
cleanupObservers() {
this.observers.forEach(observer => {
observer.disconnect();
});
this.observers = [];
console.log('DOM observers cleaned up');
}
cleanup() {
this.domReferences.clear();
this.cleanupObservers();
}
}Najczęstsza przyczyna to zapomniane event listenery i timery. Listener na obiekcie, który żyje dłużej niż komponent, na przykład na document, trzyma przy życiu wszystko, do czego sięga jego domknięcie. AbortController usuwa wiele listenerów jednym abort(), a WeakMap nie blokuje sprzątnięcia elementu DOM. W przykładzie ze zmiennymi globalnymi pamiętaj, że klasy działają w trybie strict, więc przypisanie do niezadeklarowanej zmiennej rzuci ReferenceError.
Memory Leak Detection i Monitoring
Performance API dla Memory Monitoring
Wyciek zdradza stały wzrost zużycia pamięci. Monitor co kilka sekund zapisuje rozmiar sterty i ostrzega, gdy ten rośnie bez przerwy:
// Memory monitoring utilities
class MemoryMonitor {
constructor() {
this.measurements = [];
this.isMonitoring = false;
this.alertThreshold = 50 * 1024 * 1024; // 50MB
}
startMonitoring(interval = 5000) {
if (this.isMonitoring) return;
this.isMonitoring = true;
console.log('Started memory monitoring');
const monitor = () => {
if (!this.isMonitoring) return;
const memInfo = this.getMemoryInfo();
this.measurements.push({
...memInfo,
timestamp: Date.now()
});
this.checkMemoryAlerts(memInfo);
this.trimMeasurements();
setTimeout(monitor, interval);
};
monitor();
}
stopMonitoring() {
this.isMonitoring = false;
console.log('⏹Stopped memory monitoring');
}
getMemoryInfo() {
if (performance.memory) {
return {
usedJSHeapSize: performance.memory.usedJSHeapSize,
totalJSHeapSize: performance.memory.totalJSHeapSize,
jsHeapSizeLimit: performance.memory.jsHeapSizeLimit,
usedPercent: (performance.memory.usedJSHeapSize / performance.memory.jsHeapSizeLimit) * 100
};
}
return {
usedJSHeapSize: 0,
totalJSHeapSize: 0,
jsHeapSizeLimit: 0,
usedPercent: 0
};
}
checkMemoryAlerts(memInfo) {
if (memInfo.usedJSHeapSize > this.alertThreshold) {
console.warn('High memory usage detected:', {
used: this.formatBytes(memInfo.usedJSHeapSize),
percent: memInfo.usedPercent.toFixed(2) + '%'
});
this.triggerMemoryCleanup();
}
// Check for memory leaks (constant growth)
if (this.measurements.length > 10) {
const recent = this.measurements.slice(-10);
const growth = recent[recent.length - 1].usedJSHeapSize - recent[0].usedJSHeapSize;
const timeSpan = recent[recent.length - 1].timestamp - recent[0].timestamp;
const growthRate = growth / timeSpan; // bytes per ms
if (growthRate > 1000) { // > 1KB/s growth
console.warn('Potential memory leak detected:', {
growthRate: this.formatBytes(growthRate * 1000) + '/s',
totalGrowth: this.formatBytes(growth)
});
}
}
}
triggerMemoryCleanup() {
// Force garbage collection if available (dev tools)
if (window.gc) {
window.gc();
console.log('Forced garbage collection');
}
// Cleanup event
window.dispatchEvent(new CustomEvent('memoryCleanup', {
detail: { memoryUsage: this.getMemoryInfo() }
}));
}
generateMemoryReport() {
if (this.measurements.length === 0) {
return { error: 'No measurements available' };
}
const latest = this.measurements[this.measurements.length - 1];
const oldest = this.measurements[0];
return {
currentUsage: {
used: this.formatBytes(latest.usedJSHeapSize),
total: this.formatBytes(latest.totalJSHeapSize),
limit: this.formatBytes(latest.jsHeapSizeLimit),
percent: latest.usedPercent.toFixed(2) + '%'
},
trend: {
totalGrowth: this.formatBytes(latest.usedJSHeapSize - oldest.usedJSHeapSize),
timeSpan: this.formatTime(latest.timestamp - oldest.timestamp),
measurementCount: this.measurements.length
},
recommendations: this.generateRecommendations()
};
}
generateRecommendations() {
const recommendations = [];
const latest = this.measurements[this.measurements.length - 1];
if (latest.usedPercent > 80) {
recommendations.push('Memory usage is very high - consider implementing cleanup strategies');
}
if (this.measurements.length > 5) {
const recentGrowth = this.measurements.slice(-5);
const avgGrowth = recentGrowth.reduce((sum, m, i) =>
i === 0 ? 0 : sum + (m.usedJSHeapSize - recentGrowth[i-1].usedJSHeapSize), 0
) / (recentGrowth.length - 1);
if (avgGrowth > 1024 * 1024) { // > 1MB average growth
recommendations.push('Consistent memory growth detected - check for memory leaks');
}
}
return recommendations;
}
formatBytes(bytes) {
const units = ['B', 'KB', 'MB', 'GB'];
let size = bytes;
let unitIndex = 0;
while (size >= 1024 && unitIndex < units.length - 1) {
size /= 1024;
unitIndex++;
}
return `${size.toFixed(2)} ${units[unitIndex]}`;
}
formatTime(ms) {
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
if (hours > 0) return `${hours}h ${minutes % 60}m`;
if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
return `${seconds}s`;
}
trimMeasurements() {
// Keep only last 100 measurements
if (this.measurements.length > 100) {
this.measurements = this.measurements.slice(-100);
}
}
}
// Memory leak detector
class MemoryLeakDetector {
constructor() {
this.snapshots = [];
this.leakPatterns = new Map();
}
takeSnapshot(label = 'snapshot') {
const snapshot = {
label: label,
timestamp: Date.now(),
memory: performance.memory ? {
used: performance.memory.usedJSHeapSize,
total: performance.memory.totalJSHeapSize
} : null,
objectCounts: this.countObjects()
};
this.snapshots.push(snapshot);
console.log(`Memory snapshot taken: ${label}`);
return snapshot;
}
countObjects() {
// Przybliżone liczenie obiektów (w rzeczywistości użyj dev tools)
const counts = {
arrays: 0,
objects: 0,
functions: 0,
strings: 0
};
// Symulacja - w prawdziwej implementacji użyj heap snapshot API
return counts;
}
compareSnapshots(snapshot1Label, snapshot2Label) {
const snap1 = this.snapshots.find(s => s.label === snapshot1Label);
const snap2 = this.snapshots.find(s => s.label === snapshot2Label);
if (!snap1 || !snap2) {
console.error('Snapshots not found');
return null;
}
const comparison = {
memoryGrowth: snap2.memory ? snap2.memory.used - snap1.memory.used : 0,
timeSpan: snap2.timestamp - snap1.timestamp,
objectGrowth: {},
suspiciousGrowth: []
};
// Analiza wzrostu obiektów
Object.keys(snap1.objectCounts).forEach(type => {
const growth = snap2.objectCounts[type] - snap1.objectCounts[type];
comparison.objectGrowth[type] = growth;
if (growth > 100) { // Suspicious growth threshold
comparison.suspiciousGrowth.push({
type: type,
growth: growth,
growthRate: growth / (comparison.timeSpan / 1000) // per second
});
}
});
return comparison;
}
detectLeakPatterns() {
if (this.snapshots.length < 3) return [];
const patterns = [];
const recent = this.snapshots.slice(-3);
// Check for consistent memory growth
const memoryGrowth = recent.map((snap, i) =>
i === 0 ? 0 : snap.memory.used - recent[i-1].memory.used
).slice(1);
const consistentGrowth = memoryGrowth.every(growth => growth > 0);
if (consistentGrowth) {
const avgGrowth = memoryGrowth.reduce((a, b) => a + b) / memoryGrowth.length;
patterns.push({
type: 'consistent_memory_growth',
severity: avgGrowth > 1024 * 1024 ? 'high' : 'medium',
description: `Memory consistently growing by ${(avgGrowth / 1024 / 1024).toFixed(2)}MB per measurement`,
avgGrowth: avgGrowth
});
}
return patterns;
}
}
// Global memory monitor instance
const memoryMonitor = new MemoryMonitor();
const leakDetector = new MemoryLeakDetector();
// Usage example
function startMemoryAnalysis() {
memoryMonitor.startMonitoring(2000); // Every 2 seconds
// Take initial snapshot
leakDetector.takeSnapshot('initial');
// Simulate some operations and take snapshots
setTimeout(() => {
// Simulate memory allocation
const data = new Array(100000).fill('test data');
leakDetector.takeSnapshot('after_allocation');
}, 5000);
setTimeout(() => {
// Generate memory report
const report = memoryMonitor.generateMemoryReport();
console.log('Memory Report:', report);
const patterns = leakDetector.detectLeakPatterns();
console.log('Leak Patterns:', patterns);
}, 10000);
}performance.memory działa tylko w Chromium i podaje wartości przybliżone, a window.gc istnieje tylko po uruchomieniu przeglądarki z flagą --js-flags=--expose-gc. Pewniejszą diagnozę daje DevTools: otwórz panel Memory, zrób heap snapshot, powtórz podejrzaną akcję, zrób drugi snapshot, porównaj je i znajdź obiekty zatrzymane w pamięci (retained objects).
Best Practices dla Memory Management
Proactive Memory Management
Lepiej zapobiegać niż leczyć. Komponent z budżetem pamięci sprząta nieużywane zasoby, pula obiektów (object pooling) używa ich ponownie, a WeakRef pozwala trzymać cache bez blokowania GC:
// Memory-aware component design
class MemoryAwareComponent {
constructor(config) {
this.config = config;
this.resources = new Map();
this.cleanup = new Set();
this.memoryBudget = config.memoryBudget || 10 * 1024 * 1024; // 10MB default
}
// Resource tracking
allocateResource(key, factory, size = 0) {
if (this.getCurrentMemoryUsage() + size > this.memoryBudget) {
this.performCleanup();
}
const resource = factory();
this.resources.set(key, {
data: resource,
size: size,
allocatedAt: Date.now(),
lastAccessed: Date.now()
});
return resource;
}
getResource(key) {
const resource = this.resources.get(key);
if (resource) {
resource.lastAccessed = Date.now();
return resource.data;
}
return null;
}
getCurrentMemoryUsage() {
return Array.from(this.resources.values())
.reduce((total, resource) => total + resource.size, 0);
}
performCleanup() {
console.log('Performing memory cleanup...');
const now = Date.now();
const staleThreshold = 5 * 60 * 1000; // 5 minutes
// Remove stale resources
for (const [key, resource] of this.resources) {
if (now - resource.lastAccessed > staleThreshold) {
this.deallocateResource(key);
}
}
// Run custom cleanup functions
this.cleanup.forEach(cleanupFn => {
try {
cleanupFn();
} catch (error) {
console.error('Cleanup function failed:', error);
}
});
}
deallocateResource(key) {
const resource = this.resources.get(key);
if (resource) {
// Custom cleanup if resource has cleanup method
if (resource.data && typeof resource.data.cleanup === 'function') {
resource.data.cleanup();
}
this.resources.delete(key);
console.log(`Deallocated resource: ${key}`);
}
}
addCleanupFunction(fn) {
this.cleanup.add(fn);
}
removeCleanupFunction(fn) {
this.cleanup.delete(fn);
}
destroy() {
// Cleanup all resources
this.resources.forEach((_, key) => {
this.deallocateResource(key);
});
// Run all cleanup functions
this.cleanup.forEach(cleanupFn => {
try {
cleanupFn();
} catch (error) {
console.error('Cleanup function failed during destroy:', error);
}
});
this.cleanup.clear();
console.log('Component destroyed and cleaned up');
}
}
// Object pooling dla często używanych obiektów
class ObjectPool {
constructor(factory, resetFn, initialSize = 10) {
this.factory = factory;
this.resetFn = resetFn;
this.pool = [];
this.activeObjects = new Set();
// Pre-allocate objects
for (let i = 0; i < initialSize; i++) {
this.pool.push(this.factory());
}
}
acquire() {
let obj;
if (this.pool.length > 0) {
obj = this.pool.pop();
} else {
obj = this.factory();
console.log('Created new object (pool exhausted)');
}
this.activeObjects.add(obj);
return obj;
}
release(obj) {
if (this.activeObjects.has(obj)) {
this.activeObjects.delete(obj);
// Reset object to initial state
if (this.resetFn) {
this.resetFn(obj);
}
this.pool.push(obj);
}
}
getStats() {
return {
poolSize: this.pool.length,
activeObjects: this.activeObjects.size,
totalObjects: this.pool.length + this.activeObjects.size
};
}
}
// Przykład użycia object pooling
const vectorPool = new ObjectPool(
() => ({ x: 0, y: 0, z: 0 }), // factory
(vector) => { vector.x = 0; vector.y = 0; vector.z = 0; }, // reset
50 // initial size
);
function performVectorCalculations() {
const vectors = [];
// Acquire vectors from pool instead of creating new ones
for (let i = 0; i < 100; i++) {
const vector = vectorPool.acquire();
vector.x = Math.random();
vector.y = Math.random();
vector.z = Math.random();
vectors.push(vector);
}
// Do calculations...
// Release vectors back to pool
vectors.forEach(vector => vectorPool.release(vector));
console.log('Vector pool stats:', vectorPool.getStats());
}
// WeakRef dla optional caching
class WeakRefCache {
constructor() {
this.cache = new Map();
this.finalizationRegistry = new FinalizationRegistry((key) => {
console.log(`Object with key '${key}' was garbage collected`);
this.cache.delete(key);
});
}
set(key, value) {
const weakRef = new WeakRef(value);
this.cache.set(key, weakRef);
this.finalizationRegistry.register(value, key);
}
get(key) {
const weakRef = this.cache.get(key);
if (!weakRef) return null;
const value = weakRef.deref();
if (value === undefined) {
// Object was garbage collected
this.cache.delete(key);
return null;
}
return value;
}
has(key) {
return this.get(key) !== null;
}
delete(key) {
this.cache.delete(key);
}
size() {
// Clean up dead references
for (const [key, weakRef] of this.cache) {
if (weakRef.deref() === undefined) {
this.cache.delete(key);
}
}
return this.cache.size;
}
}WeakRef tworzy słabą referencję, która nie blokuje garbage collection: deref() zwraca obiekt albo undefined, gdy GC już go zabrał. Callback FinalizationRegistry może się nigdy nie wywołać, więc traktuj go jako sprzątanie pomocnicze, nie logikę aplikacji.
Memory Profiling Tools
Na koniec profiler, który mierzy zużycie pamięci wokół wybranej metody i dołącza się do niej przez dekorator:
// Development memory profiling utilities
class MemoryProfiler {
constructor() {
this.profiles = new Map();
this.isProfilingEnabled = process.env.NODE_ENV === 'development';
}
startProfile(name) {
if (!this.isProfilingEnabled) return;
const profile = {
name: name,
startTime: performance.now(),
startMemory: performance.memory ? {
used: performance.memory.usedJSHeapSize,
total: performance.memory.totalJSHeapSize
} : null,
snapshots: []
};
this.profiles.set(name, profile);
console.log(`Started memory profile: ${name}`);
}
snapshot(profileName, label) {
if (!this.isProfilingEnabled) return;
const profile = this.profiles.get(profileName);
if (!profile) return;
const snapshot = {
label: label,
timestamp: performance.now(),
memory: performance.memory ? {
used: performance.memory.usedJSHeapSize,
total: performance.memory.totalJSHeapSize
} : null
};
profile.snapshots.push(snapshot);
console.log(`Memory snapshot: ${profileName}.${label}`);
}
endProfile(name) {
if (!this.isProfilingEnabled) return;
const profile = this.profiles.get(name);
if (!profile) return;
profile.endTime = performance.now();
profile.endMemory = performance.memory ? {
used: performance.memory.usedJSHeapSize,
total: performance.memory.totalJSHeapSize
} : null;
const report = this.generateProfileReport(profile);
console.log(`Memory profile completed: ${name}`, report);
return report;
}
generateProfileReport(profile) {
const duration = profile.endTime - profile.startTime;
let memoryGrowth = 0;
if (profile.startMemory && profile.endMemory) {
memoryGrowth = profile.endMemory.used - profile.startMemory.used;
}
const snapshots = profile.snapshots.map((snapshot, index) => {
const prevSnapshot = index > 0 ? profile.snapshots[index - 1] :
{ memory: profile.startMemory, timestamp: profile.startTime };
return {
label: snapshot.label,
timeDelta: snapshot.timestamp - prevSnapshot.timestamp,
memoryDelta: snapshot.memory && prevSnapshot.memory ?
snapshot.memory.used - prevSnapshot.memory.used : 0
};
});
return {
duration: duration.toFixed(2) + 'ms',
memoryGrowth: memoryGrowth,
memoryGrowthFormatted: this.formatBytes(memoryGrowth),
snapshots: snapshots,
recommendations: this.generateProfileRecommendations(profile, memoryGrowth)
};
}
generateProfileRecommendations(profile, memoryGrowth) {
const recommendations = [];
if (memoryGrowth > 1024 * 1024) { // > 1MB growth
recommendations.push('Significant memory growth detected - review object allocations');
}
if (profile.snapshots.length > 0) {
const biggestGrowth = Math.max(...profile.snapshots.map((s, i) => {
const prev = i > 0 ? profile.snapshots[i-1] : { memory: profile.startMemory };
return s.memory && prev.memory ? s.memory.used - prev.memory.used : 0;
}));
if (biggestGrowth > 512 * 1024) { // > 512KB single growth
recommendations.push('Large single allocation detected - consider chunking or streaming');
}
}
return recommendations;
}
formatBytes(bytes) {
if (bytes === 0) return '0 B';
const k = 1024;
const sizes = ['B', 'KB', 'MB', 'GB'];
const i = Math.floor(Math.log(Math.abs(bytes)) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
}
// Global profiler instance
const memoryProfiler = new MemoryProfiler();
// Decorator dla automatycznego profilowania funkcji
function profileMemory(name) {
return function(target, propertyKey, descriptor) {
const originalMethod = descriptor.value;
descriptor.value = function(...args) {
const profileName = name || `${target.constructor.name}.${propertyKey}`;
memoryProfiler.startProfile(profileName);
try {
const result = originalMethod.apply(this, args);
if (result instanceof Promise) {
return result.finally(() => {
memoryProfiler.endProfile(profileName);
});
} else {
memoryProfiler.endProfile(profileName);
return result;
}
} catch (error) {
memoryProfiler.endProfile(profileName);
throw error;
}
};
return descriptor;
};
}
// Usage example
class DataProcessor {
@profileMemory('processLargeDataset')
processLargeDataset(data) {
memoryProfiler.snapshot('processLargeDataset', 'start');
// Process data in chunks
const chunks = this.chunkArray(data, 1000);
const results = [];
chunks.forEach((chunk, index) => {
memoryProfiler.snapshot('processLargeDataset', `chunk_${index}`);
const processed = chunk.map(item => this.transformItem(item));
results.push(...processed);
});
memoryProfiler.snapshot('processLargeDataset', 'end');
return results;
}
chunkArray(array, size) {
const chunks = [];
for (let i = 0; i < array.length; i += size) {
chunks.push(array.slice(i, i + size));
}
return chunks;
}
transformItem(item) {
return { ...item, processed: true, timestamp: Date.now() };
}
}@profileMemory to dekorator w stylu TypeScriptu z opcją experimentalDecorators. W czystym JavaScripcie dekoratory są wciąż propozycją na etapie Stage 3, więc ten kod wymaga kompilatora.
Podsumowanie
Zarządzanie pamięcią w JavaScript wymaga:
- Zrozumienia Garbage Collection - jak działa i kiedy się uruchamia
- Świadomości Memory Leaks - główne przyczyny i sposoby unikania
- Proaktywnego podejścia - monitoring i cleanup
- Właściwych wzorców - object pooling, WeakMap, AbortController
- Narzędzi diagnostycznych - profiling i monitoring
Kluczowe zasady: sprzątaj po sobie listenery, timery i obserwatory, używaj WeakMap i WeakSet dla opcjonalnych referencji, monitoruj pamięć na produkcji, stosuj object pooling dla często alokowanych obiektów, unikaj przypadkowych zmiennych globalnych i testuj aplikację pod kątem wycieków. Moja rada: każde addEventListener, setInterval i observe pisz od razu w parze z kodem, który je usuwa. W edytorze poniżej przetestujesz garbage collection na przykładach, a w kolejnej lekcji wracamy do TypeScriptu i plików .d.ts.
Pamiętaj: garbage collector sprząta tylko to, do czego nie prowadzi już żadna ścieżka, więc ścieżki do niepotrzebnych danych musisz przecinać sam.
Kod do tej lekcji: index.js
// Garbage Collection i Memory Leaks w JavaScript
console.log("Laboratorium Zarządzania Pamięcią DNA");
console.log("Analiza garbage collection i memory leaks\n");
// ====================================
// 1. JAK DZIAŁA PAMIĘĆ W JAVASCRIPT
// ====================================
console.log("=== 1. Typy przechowywania danych ===\n");
// Stack (wartości prymitywne)
let dinosaurCount = 5;
let parkName = "Jurassic Park";
let isActive = true;
console.log("Stack memory (wartości prymitywne):");
console.log("- dinosaurCount:", dinosaurCount);
console.log("- parkName:", parkName);
console.log("- isActive:", isActive);
// Heap (obiekty i referencje)
let dinosaur1 = { name: "T-Rex", age: 68000000 };
let dinosaur2 = dinosaur1; // Ta sama referencja!
console.log("\nHeap memory (obiekty):");
console.log("dinosaur1:", dinosaur1);
console.log("dinosaur2:", dinosaur2);
console.log("dinosaur1 === dinosaur2:", dinosaur1 === dinosaur2);
// ====================================
// 2. GARBAGE COLLECTION
// ====================================
console.log("\n=== 2. Garbage Collection ===\n");
// Mark and Sweep Algorithm
function demonstrateGC() {
let tempDinosaur = { name: "Velociraptor", age: 75000000 };
console.log("Stworzono tymczasowego dinozaura:", tempDinosaur.name);
// Po wyjściu z funkcji, tempDinosaur jest oznaczony do usunięcia
// Garbage Collector automatycznie zwolni pamięć
}
demonstrateGC();
console.log("Funkcja zakończona - pamięć zostanie zwolniona przez GC");
// Referencje i GC
let dino = { name: "Triceratops" };
let dinoRef1 = dino;
let dinoRef2 = dino;
console.log("\nLiczba referencji do obiektu: 3");
dino = null;
console.log("Po usunięciu 'dino': 2 referencje pozostają");
dinoRef1 = null;
console.log("Po usunięciu 'dinoRef1': 1 referencja pozostaje");
dinoRef2 = null;
console.log("Po usunięciu 'dinoRef2': 0 referencji - obiekt zostanie usunięty przez GC!");
// ====================================
// 3. MEMORY LEAKS - TYPOWE PRZYCZYNY
// ====================================
console.log("\n=== 3. Memory Leaks - Częste błędy ===\n");
// LEAK 1: Zmienne globalne
console.log("LEAK 1: Niezamierzone zmienne globalne");
function createAccidentalGlobal() {
// Brak 'let', 'const' lub 'var' - tworzy globalną zmienną!
// accidentalDinosaur = { name: "Leaked Dino" }; // NIE RÓB TEGO!
console.log("Zawsze używaj let/const/var!");
}
// LEAK 2: Zapomniane timery
console.log("\nLEAK 2: Zapomniane timery/intervals");
let leakyTimer;
function demonstrateTimerLeak() {
const hugeData = new Array(1000000).fill("DNA sequence");
leakyTimer = setInterval(() => {
// hugeData jest zamknięty w closure i nigdy nie zostanie zwolniony!
console.log("Timer działa z dostępem do hugeData");
}, 1000);
// Rozwiązanie: Zawsze czyść timery
// clearInterval(leakyTimer);
}
console.log("Timer utworzony - pamięć rośnie!");
console.log("Rozwiązanie: clearInterval(leakyTimer);");
// LEAK 3: DOM references
console.log("\nLEAK 3: Przechowywanie referencji DOM");
const domReferences = [];
function demonstrateDOMLeaks() {
// Symulacja DOM elementu
const element = { id: "dino-card-1", data: "Massive data..." };
domReferences.push(element);
// Nawet jeśli element zostanie usunięty z DOM,
// referencja w tablicy nadal go trzyma w pamięci!
console.log("Element dodany do tablicy referencji");
}
// LEAK 4: Closures
console.log("\nLEAK 4: Nadużycie closures");
function createLeakyClosure() {
const hugeArray = new Array(1000000).fill({ dino: "data" });
return function() {
// Closure trzyma referencję do całego hugeArray
console.log("Rozmiar tablicy:", hugeArray.length);
};
}
const leakyFunction = createLeakyClosure();
console.log("Closure utworzony - hugeArray pozostaje w pamięci");
// ====================================
// 4. JAK UNIKAĆ MEMORY LEAKS
// ====================================
console.log("\n=== 4. Dobre praktyki ===\n");
// 1. Czyść timery
function properTimerUsage() {
const timer = setInterval(() => {
console.log("Timer działa");
}, 1000);
// Cleanup
setTimeout(() => {
clearInterval(timer);
console.log("Timer został wyczyszczony");
}, 3000);
}
// 2. Używaj WeakMap/WeakSet
console.log("Używaj WeakMap dla metadata:");
const metadataMap = new WeakMap();
let dinosaurObject = { name: "Stegosaurus" };
metadataMap.set(dinosaurObject, { discovered: 1877, location: "Colorado" });
console.log("Metadata dodana do WeakMap");
dinosaurObject = null; // Obiekt może być usunięty przez GC!
console.log("Obiekt usunięty - metadata również zostanie usunięta");
// 3. Proper event listeners cleanup
class DinosaurMonitor {
constructor() {
this.dinosaurs = [];
this.eventHandler = this.onUpdate.bind(this);
}
onUpdate(data) {
this.dinosaurs.push(data);
}
start() {
// addEventListener('update', this.eventHandler);
console.log("Monitor started z bind()");
}
stop() {
// removeEventListener('update', this.eventHandler);
console.log("Monitor stopped - event listener removed");
}
}
// 4. Nullify references
console.log("\nNullifikuj duże obiekty gdy nie są potrzebne:");
let bigDinosaurData = new Array(100000).fill({ genome: "ATCG..." });
console.log("Duży obiekt utworzony");
// Gdy skończysz pracę z danymi:
bigDinosaurData = null;
console.log("Obiekt nullified - gotowy do GC");
// ====================================
// 5. MONITORING PAMIĘCI
// ====================================
console.log("\n=== 5. Monitoring pamięci ===\n");
if (performance.memory) {
console.log("Informacje o pamięci:");
console.log("- Used JS Heap:", performance.memory.usedJSHeapSize);
console.log("- Total JS Heap:", performance.memory.totalJSHeapSize);
console.log("- Limit:", performance.memory.jsHeapSizeLimit);
} else {
console.log("performance.memory niedostępne (użyj Chrome DevTools)");
}
console.log("\nNarzędzia do debugowania:");
console.log("1. Chrome DevTools → Memory → Heap Snapshot");
console.log("2. Performance profiler");
console.log("3. Memory timeline");
console.log("\nPamiętaj:");
console.log("- Zawsze czyść timery i event listeners");
console.log("- Używaj WeakMap/WeakSet gdy to możliwe");
console.log("- Nullifikuj duże obiekty po użyciu");
console.log("- Unikaj globalnych zmiennych");
console.log("- Monitoruj zużycie pamięci w DevTools");Hasła z dokumentacji w tej lekcji
Widzisz błąd w tej lekcji?
Sprawdź się
Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.
1. Co jest najczęstszą przyczyną memory leak w JavaScript?
2. Który mechanizm jest główną strategią Garbage Collection w nowoczesnym JavaScript?
To 2 z 3 pytań do tej lekcji. Pozostałe rozwiążesz w grze.
Zadania praktyczne w grze
- Edytor kodu
Znajdź i napraw memory leak w podanym kodzie.
- Edytor kodu
Usuń niepotrzebne referencje (globalne kolekcje, domknięcia) i nieusunięte event listenery.
- Układanie w pionie
Ułóż fazy procesu garbage collection w odpowiedniej kolejności:
- Układanie w pionie
Ułóż etapy identyfikacji memory leak w aplikacji w odpowiedniej kolejności: