Profilowanie i wykrywanie wycieków pamięci
Poznaj sposoby mierzenia użycia procesora i pamięci w Node.js, przechwytywania profili oraz wykrywania wycieków pamięci, zanim doprowadzą do awarii środowiska produkcyjnego.
Profilowanie i wykrywanie wycieków pamięci to bezpłatna lekcja Node.js Backend Development Bootcamp na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Node.js Backend Development Bootcamp, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Node.js Backend Development Bootcamp zawiera 4 lekcji w sumie.
Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.
Why Profile?
You cannot optimize what you cannot measure. Profiling reveals where your app spends time (CPU) and memory, so you fix the real bottleneck instead of guessing.
A common rule: measure, change one thing, measure again.
Measuring Memory Usage
Node exposes live memory stats via process.memoryUsage(). The key field is heapUsed — the JavaScript heap your code allocates.
const m = process.memoryUsage();
console.log('Heap used MB:', (m.heapUsed / 1048576).toFixed(1));What is a Memory Leak?
A memory leak happens when objects that are no longer needed are still referenced, so the garbage collector cannot free them. Over time heapUsed climbs and the process eventually crashes.
Common Leak Sources
Most Node.js leaks come from a handful of patterns:
- Growing global arrays or caches that never evict
- Forgotten event listeners
- Closures capturing large objects
- Timers that are never cleared
const cache = [];
app.get('/x', (req, res) => {
cache.push(req.body); // never cleared = leak
res.end();
});Timing Code Sections
For quick CPU timing, console.time and console.timeEnd measure how long a block takes.
console.time('work');
for (let i = 0; i < 1e6; i++) {}
console.timeEnd('work');High-Resolution Timing
For precise benchmarks use the Performance API, which gives sub-millisecond resolution unaffected by clock changes.
const { performance } = require('perf_hooks');
const start = performance.now();
doWork();
console.log('Took', performance.now() - start, 'ms');CPU Profiling with --prof
Run Node with the --prof flag to record a V8 CPU profile. It writes a log file you process into a readable report.
// node --prof app.js
// node --prof-process isolate-*.log > report.txtHeap Snapshots
A heap snapshot captures every object in memory at a moment. Take two snapshots over time and compare them to find what keeps growing.
Capture them via Chrome DevTools (connect with --inspect) or programmatically.
// node --inspect app.js
// then open chrome://inspect and take heap snapshotsThe Clinic.js Toolkit
The clinic tool suite visualizes performance problems. Clinic Doctor diagnoses issues, while Clinic Heap Profiler tracks allocations.
// npm install -g clinic
// clinic doctor -- node app.jsDetecting a Leak in Practice
Log heapUsed periodically under steady load. If it trends upward and never returns after garbage collection, you likely have a leak — then snapshot to find the culprit.
setInterval(() => {
const mb = process.memoryUsage().heapUsed / 1048576;
console.log('Heap MB:', mb.toFixed(1));
}, 5000);Fixing Leaks
Once found, common fixes are:
- Cap caches with an LRU strategy
- Remove listeners with
removeListener/off - Clear timers with
clearInterval - Avoid capturing large objects in long-lived closures
Quick Check
Test your profiling knowledge.
Recap
You learned to profile and find leaks:
- Measure memory with
process.memoryUsage() - Time code with
console.timeand the Performance API - Capture CPU profiles with
--profand heap snapshots with--inspect - Spot leaks via climbing
heapUsed; fix with bounded caches and cleaned-up listeners/timers
Measuring first turns optimization from guesswork into engineering.
Często zadawane pytania
Czy lekcja „Profilowanie i wykrywanie wycieków pamięci” jest bezpłatna?
Tak — pełny tekst „Profilowanie i wykrywanie wycieków pamięci” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Node.js Backend Development Bootcamp, przejdź na CoddyKit PRO. Kurs Node.js Backend Development Bootcamp zawiera 4 lekcji w sumie.
Co nauczysz się w „Profilowanie i wykrywanie wycieków pamięci”?
Poznaj sposoby mierzenia użycia procesora i pamięci w Node.js, przechwytywania profili oraz wykrywania wycieków pamięci, zanim doprowadzą do awarii środowiska produkcyjnego. Ćwiczysz Node.js Backend Development Bootcamp z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.
Czy potrzebuję doświadczenia, aby zacząć Node.js Backend Development Bootcamp?
Nie wymagamy żadnego doświadczenia. Node.js Backend Development Bootcamp w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.
Ile czasu zajmuje lekcja „Profilowanie i wykrywanie wycieków pamięci”?
Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.
Czy mogę pisać i uruchamiać kod w tej lekcji Node.js Backend Development Bootcamp?
Tak. Każda lekcja Node.js Backend Development Bootcamp zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.
Wszystkie lekcje w tym kursie
- Strategie buforowania dla Node.js
- Równoważenie obciążenia aplikacji Node.js
- Optymalizacja pętli zdarzeń Node.js
- Profilowanie i wykrywanie wycieków pamięci