모든 프레임워크에 대한 기능 메모이저

WBOY
풀어 주다: 2024-09-08 22:31:03
원래의
539명이 탐색했습니다.

기억? - JavaScript 함수를 위한 경량 메모이제이션(1.3KB)

동일한 매개변수로 실행되는 기능에 대한 캐시 메커니즘(메모이저)(단 1.3KB)

이 프로젝트는 비용이 많이 드는 함수 호출의 결과를 캐시하여 JavaScript 또는 TypeScript 프로젝트의 성능을 향상시키기 위한 메모 기능을 제공합니다. 메모를 하면 동일한 인수로 반복 호출하면 캐시된 결과가 반환되므로 실행 속도가 빨라집니다.

이 모듈은 React의 useMemo 후크처럼 작동하지만 필수 React는 아닙니다. 모든 프레임워크나 순수 자바스크립트 프로젝트를 사용할 수 있습니다

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

특징

  • 함수 메모: 동일한 인수를 사용하여 함수 호출 결과를 캐시합니다.
  • 종속성 추적: 종속성이 변경되면 캐시를 업데이트합니다.
  • 유연성: JavaScript와 TypeScript 프로젝트 모두에서 사용 가능
  • CPU 집약적인 작업이나 복잡한 계산을 위한 최고의 솔루션
  • 연결이 끊어진 기능은 메모리에서 삭제됩니다. 이 기능에 속한 캐시도 삭제됩니다.
  • WeakMap 기반 캐시 저장소
  • WeakMap 약한 참조 링크와 통신할 수 없는 메서드의 연결을 끊고 가비지 수집기가 시작되도록 트리거합니다

왜 memofy를 사용해야 할까요?

Memofy를 사용하면 함수 실행 시간을 최대 1500배까지 줄일 수 있습니다. 무거운 기능을 테스트하여 얻은 결과는 다음과 같습니다. ??

테스트 케이스 함수 실행 시간(ms)
Test Case Function Execute Time (ms)
With Memofy (CACHED) 0.083 ms
Without Memofy 57.571 ms
Memofy 포함(캐시됨) 0.083ms

메모피 없이

57.571ms
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
로그인 후 복사
NPM
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(예: globalContex)를 사용하는 경우 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 Repository

위 내용은 모든 프레임워크에 대한 기능 메모이저의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!