首页 > web前端 > js教程 > 正文

每个框架的函数存储器

WBOY
发布: 2024-09-08 22:31:03
原创
539 人浏览过

记忆? - JavaScript 函数的轻量级记忆 (1.3KB)

使用相同参数执行的函数的缓存机制(memoizer)(仅 1.3 KB)

该项目提供了 memoize 函数,通过缓存昂贵的函数调用结果来提高 JavaScript 或 TypeScript 项目的性能。通过记忆,使用相同参数重复调用将返回缓存的结果,从而加快执行速度。

这个模块的工作原理类似于 React 的 useMemo hook,但不需要 React。您可以使用任何框架或纯 javascript 项目

Function memoizer for every framework Function memoizer for every framework Function memoizer for every framework

特征

  • 函数记忆:缓存具有相同参数的函数调用结果。
  • 依赖项跟踪:如果依赖项发生变化,则更新缓存。
  • 灵活性:可用于 JavaScript 和 TypeScript 项目。
  • CPU密集型运算或复杂计算的最佳解决方案
  • 断开连接的函数将从内存中删除。属于该函数的缓存也会被删除。
  • 基于WeakMap的缓存存储
  • WeakMap 断开无法与弱引用链接通信的方法,并触发垃圾收集器启动

我们为什么要使用memofy?

使用 Memofy,您可以将函数的执行时间减少多达 1500 倍。以下结果是通过重函数测试得到的。 ??

测试用例 函数执行时间(毫秒) 标题>
Test Case Function Execute Time (ms)
With Memofy (CACHED) 0.083 ms
Without Memofy 57.571 ms
使用 Memofy(缓存) 0.083 毫秒

没有 Memofy

57.571 毫秒 表>
import memofy from "memofy";

const dep1 = /** Variable to track change */

const heavyMethod = memofy((arg1, arg2, ...args) => {
 // calculate something then return
}, [dep1, dep2, ...deps]);

// heavyMethod looks at the deps and arguments every time it is called.
// If there is no change, it brings it from the cache. If there is a change, it runs the function again
登录后复制
而且非常简单

安装
npm install memofy
登录后复制
国家公共管理
yarn add memofy
登录后复制

使用案例

没有 deps 参数

在下面的过程中,当使用相同的参数再次调用 concatPhoneNumber 方法时,该函数不会再次执行,而是从缓存中获取结果。
import memofy from "memofy";

const concatPhoneNumber = (extension, number) => {
  // Heavy calculation
  // return result
};

const memoizedConcatPhoneNumber = memofy(concatPhoneNumber, []);

memoizedConcatPhoneNumber(90, 555); // Runs concatPhoneNumber once
memoizedConcatPhoneNumber(90, 555); // Don't run because fetched from cache (same parameter)
memoizedConcatPhoneNumber(90, 552); // Runs concatPhoneNumber because params is changed
登录后复制

带 deps 参数

如果您希望该方法根据某些依赖关系以相同的参数再次运行,可以按如下方式传递 deps 参数。
import memofy from "memofy";

const product = { title: "Test product", price: 10 };

const calculateTax = (taxRatio) => {
  // Calculate tax by product price
  // Heavy calculation
  return taxRatio * product.price;
};

const memoizedCalculateTax = memofy(calculateTax, [product]);

calculateTax(2); // Runs calculateTax when first run -> 20
calculateTax(2); // // Don't run because fetched from cache (same parameter and same deps) -> 20

product.price = 40;
calculateTax(3); // Runs calculateTax because product dep changed -> 120
登录后复制
import memofy from "memofy";

const products = [
  /**Let's say there are more than 100 products */
];

// It is costly to cycle through 100 products each time. Just keep the result in the cache when it runs once.
const getTotalPrice = (fixPrice) => {
  return products.reduce((acc, curr) => acc + curr.price, 0);
};

const _getTotalPrice = memofy(getTotalPrice, [products]);
getTotalPrice(0); // Runs getTotalPrice once
getTotalPrice(0); // Don't run because fetched from cache
products.push({
  /** a few products */
});
getTotalPrice(2); // Runs again getTotalPrice because products and parameter changed
登录后复制

有上下文

如果要缓存的函数中使用了 context(this, globalContex e.g),则可以传递 context 参数。
import memofy from "memofy";

this.user.name = "Jack"; // For example inject name to context

const getName = (suffix) => {
  return `${suffix} ${this.user.name}`;
};
const memoizedGetName = memofy(getName, [], this);
memoizedGetName("Mr"); // Result is Mr Jack

this.user.name = "John";
memoizedGetName("Mr"); // Result is Mr John because context data changed
登录后复制

type Args = Array<any>;

type Deps = Readonly<Array<any>>;

type MemoizedFunction<A extends Args, ReturnType> = (...args: A) => ReturnType;

declare function memofy<A extends Args, ReturnType extends any>(
  _functionToMemoize: (...args: Array<unknown>) => ReturnType,
  _deps?: Deps,
  _context?: unknown
): MemoizedFunction<A, ReturnType>;
登录后复制

打字稿声明

绩效结果

区分素数的复杂函数的性能结果。性能测试
Case ms
First execute time (no caching) > 52.08 ms
Second execute time (caching) < 0.03 ms
and subsequent execution (caching) < 0.03 ms

测试覆盖率结果

针对所有情况和所有参数类型编写了测试。测试
File % Stmts % Branch % Funcs % Lines
All files 90.69 86.95 100 94.59
lib 88.88 92.3 100 87.5
index.ts 88.88 92.3 100 87.5
lib/store 92 80 100 100
DependencyCacheStore.ts.ts 90 75 100 100
FunctionCacheStore.ts 93.33 83.33 100 100

贡献

这是开源软件。如果您愿意,可以通过成为贡献者来支持它。 Github 存储库

以上是每个框架的函数存储器的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!