Memoization 将函数的结果缓存,并以其参数作为键,因此使用相同输入的重复调用会立即返回缓存结果,而不是重新计算。它用内存换取速度,仅适用于纯函数(相同输入→相同输出,无副作用)。
一个通用的 memoize 包装器
js
() {
cache = ();
{
key = .(args);
(cache.(key)) {
cache.(key);
}
result = (...args);
cache.(key, result);
result;
};
}
= n => { n * n; };
fastSquare = (slowSquare);
();
();
