🛠️ 처음부터 만드는 Memoize — 함수 결과 캐싱하기
기본 구현
```javascript
function memoize(fn) {
const cache = new Map();
return function(...args) {
const key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key);
}
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
}
```
사용 예제
```javascript
const fibonacci = memoize((n) => {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
});
console.time('first');
fibonacci(40);
console.timeEnd('first'); // ~100ms
console.time('second');
fibonacci(40); // 캐시에서 즉시 반환
console.timeEnd('second'); // <1ms
```
주의점
심화: WeakMap으로 메모리 관리
객체를 캐시 키로 쓸 때 WeakMap을 쓰면 자동 정리됩니다:
```javascript
function memoizeWithWeakMap(fn) {
const cache = new WeakMap();
return function(obj) {
if (cache.has(obj)) return cache.get(obj);
const result = fn(obj);
cache.set(obj, result);
return result;
};
}
```
React의 `useMemo`, `memo`도 같은 원리입니다. 불필요한 재계산을 피해 성능을 최적화하는 핵심 기법입니다.
Comments (0)
💬
No comments yet.
Be the first to comment!