Hari 21: Performance & Optimisasi
55 min
Last updated 09 Apr 2026
Memoization — Cache Hasil Komputasi
function memoize(fn) {
const cache = new Map();
return function(...args) {
const key = JSON.stringify(args);
if (cache.has(key)) {
console.log(`Cache hit: ${key}`);
return cache.get(key);
}
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
}
const fibonacci = memoize(function fib(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
});
console.log(fibonacci(10)); // 55 (cepat berkat memoization)
console.log(fibonacci(10)); // Cache hit: [10]
Debounce & Throttle
// Debounce — tunda eksekusi, reset jika dipanggil lagi
function debounce(fn, delay) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
// Throttle — batasi frekuensi eksekusi
function throttle(fn, limit) {
let inThrottle = false;
return (...args) => {
if (!inThrottle) {
fn(...args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
💡
Notice: fib(8) pertama: 9 calls (misses). fib(8) kedua & ketiga: langsung hit cache. Total 9 cache entries untuk fib(0) sampai fib(8).
Assignment
Implementasi memoize yang juga track berapa kali cache hit vs miss. Hitung fibonacci(8) 3 kali dan tampilkan statistiknya.
Expected output:
21
21
21
Hits: 2, Misses: 9, Cached: 9
JS
script.js
Solution
Output