首頁 > 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學習者快速成長!