🛠️ 처음부터 만드는 Memoize — ramda-style 함수 결과 캐싱 12줄 구현
메모이제이션이란?
같은 입력에 같은 결과를 반환하는 함수의 연산 결과를 캐싱해, 재계산을 피하는 최적화 기법입니다.
```js
// fibonacci(40)을 10번 호출해도 첫 번째만 계산
const memo = memoize(fibonacci);
memo(40); // 계산 100ms
memo(40); // 캐시 < 1ms
memo(40); // 캐시 < 1ms
```
12줄 구현
```js
function memoize(fn) {
const cache = new Map();
return function memoized(...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;
};
}
```
실전 예제
```js
// 비싼 계산 함수
const expensiveCalc = (n) => {
let sum = 0;
for (let i = 0; i < 1e8; i++) sum += i * n;
return sum;
};
const memo = memoize(expensiveCalc);
console.time('첫 호출');
memo(5); // 계산 수행
console.timeEnd('첫 호출'); // ~50ms
console.time('캐시 히트');
memo(5); // 캐시 반환
console.timeEnd('캐시 히트'); // < 1ms
```
심화: 캐시 크기 제한
```js
function memoizeWithLimit(fn, maxSize = 100) {
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);
if (cache.size > maxSize) {
cache.delete(cache.keys().next().value);
}
return result;
};
}
```
실전 팁
실제 라이브러리
👁 0 views
Comments (0)
💬
No comments yet.
Be the first to comment!