Skip to content

Elevate your application's performance with πŸš€ Performance Decorators! This comprehensive TypeScript library offers powerful tools for performance monitoring and optimization, making it easier to track and resolve bottlenecks in both Node.js and browser environments.

License

Notifications You must be signed in to change notification settings

RyanMyrvold/Performance-Decorators

πŸš€ Performance Decorators: A TypeScript Library for Efficient Performance Monitoring & Optimization

Elevate your application's performance with Performance Decorators! This TypeScript library provides powerful tools for seamless performance monitoring and optimization in both Node.js and browser environments. Simplify identifying bottlenecks and ensure your applications run efficiently with easy-to-use decorators.

Unit Tests npm npm GitHub Issues GitHub Repo stars

🌟 Features

Debugging Decorators

  • LogExecutionTime: Method decorator β€” Measures and logs execution time (supports sync, async, and thrown errors).
  • LogMemoryUsage: Method decorator β€” Logs memory delta (bytes) before and after method execution when supported.
  • LogMethodError: Method decorator β€” Catches, logs errors (including non-Error throws), and optionally rethrows.
  • WarnMemoryLeak: Class decorator β€” Periodically checks memory usage and warns if it grows past a threshold. Node.js and browsers supported.
  • WarnPerformanceThreshold: Method decorator β€” Warns (via console.warn and optional handler) if execution time exceeds a threshold.
  • LogNetworkRequests: Method decorator β€” Wraps fetch() inside the decorated method scope and logs each request (method, URL, status, timing). Works if globalThis.fetch is available.
  • LogReturnValue: Method decorator β€” Logs the returned value of a method (sync or async) using a supplied logger or console.log.

Optimization Decorators

  • AutoRetry: Method decorator β€” Retries async operations up to N times with configurable delay until success or final failure.
  • Debounce: Method decorator β€” Coalesces rapid successive calls into a single execution after the specified delay. Returns a Promise.
  • LazyLoad: (Getter or zero-arg method) decorator β€” Lazily computes and caches the result on first access; subsequent calls retrieve cached value.
  • Memoize: Method decorator β€” Caches results per-instance and per-method key (default key = JSON.stringify args unless a custom key builder is provided).
  • Throttle: Method decorator β€” Ensures a method isn’t executed more than once per specified window; fires immediately (leading) and coalesces a trailing call if additional invocations happen within the window.

πŸ“¦ Installation

npm install performance-decorators

πŸ› οΈ Usage Examples

Debugging Decorators Usage

Log Execution Time

import { LogExecutionTime } from "performance-decorators/debugging";

class PerformanceExample {
  @LogExecutionTime()
  quickMethod() {
    // ...
  }

  @LogExecutionTime((ms, methodName) =>
    console.debug(`[${methodName}] executed in ${ms.toFixed(2)}ms`)
  )
  detailedMethod() {
    // ...
  }
}

Log Memory Usage

import { LogMemoryUsage } from "performance-decorators/debugging";

class PerformanceExample {
  @LogMemoryUsage()
  methodWithMemoryUse() {
    // ...
  }

  @LogMemoryUsage((deltaBytes, methodName) =>
    console.debug(`[${methodName}] Ξ”${deltaBytes} bytes`)
  )
  detailedMemoryMethod() {
    // ...
  }
}

Log Method Error

import { LogMethodError } from "performance-decorators/debugging";

class PerformanceExample {
  @LogMethodError()
  methodWithError() {
    throw new Error("Example error");
  }

  @LogMethodError(false, (error, methodName) =>
    console.error(`[${methodName}] error: ${error.message}`)
  )
  methodWithCustomErrorHandling() {
    throw new Error("Custom error");
  }
}

Warn Memory Leak

import { WarnMemoryLeak } from "performance-decorators/debugging";

/**
 * @param checkIntervalMs – interval between memory checks (default 30 000ms)
 * @param thresholdPercent – percent increase that triggers warning (default 20%)
 * @param logger – warning logger (default console.warn)
 */
@WarnMemoryLeak(30000, 20, console.warn)
class MyMonitoredClass {
  // ...
}

Warn Performance Threshold

import { WarnPerformanceThreshold } from "performance-decorators/debugging";

class PerformanceExample {
  @WarnPerformanceThreshold() // default threshold ~100ms
  defaultThresholdMethod() {
    // ...
  }

  @WarnPerformanceThreshold(200, (ms, methodName) =>
    console.warn(`[${methodName}] took ${ms.toFixed(2)}ms`)
  )
  customThresholdMethod() {
    // ...
  }
}

Log Network Requests

import { LogNetworkRequests } from "performance-decorators/debugging";

class ApiService {
  @LogNetworkRequests()
  async fetchData(url: string) {
    const r = await fetch(url);
    return r.json();
  }

  @LogNetworkRequests((log) => {
    console.debug(
      `[Fetch] ${log.method} ${log.url} β†’ ${log.status} in ${(log.end - log.start).toFixed(2)}ms`
    );
  })
  async fetchWithCustomLogger(url: string) {
    const r = await fetch(url);
    return r.json();
  }
}

Log Return Value

import { LogReturnValue } from "performance-decorators/debugging";

class ExampleService {
  @LogReturnValue()
  calculateSum(a: number, b: number): number {
    return a + b;
  }

  @LogReturnValue((value, methodName) =>
    console.debug(`[${methodName}] returned`, value)
  )
  async fetchData(url: string): Promise<any> {
    const r = await fetch(url);
    return r.json();
  }
}

Optimization Decorators Usage

AutoRetry

import { AutoRetry } from "performance-decorators/optimization";

class DataService {
  @AutoRetry(3, 1000) // up to 3 retries, 1 000ms delay
  async fetchData(url: string) {
    const r = await fetch(url);
    if (!r.ok) {
      throw new Error(`HTTP ${r.status}`);
    }
    return r.json();
  }
}

Debounce

import { Debounce } from "performance-decorators/optimization";

class SearchComponent {
  @Debounce(300)
  async onSearch(term: string) {
    console.debug(`Searching for ${term}`);
    return fetch(`/api/search?q=${encodeURIComponent(term)}`).then(r => r.json());
  }
}

const search = new SearchComponent();
search.onSearch("hello"); // only one of rapid calls executes

LazyLoad

import { LazyLoad } from "performance-decorators/optimization";

class ExpensiveComputation {
  @LazyLoad()
  get data() {
    console.debug("Initializing expensive data");
    return Array.from({ length: 1_000_000 }, (_, i) => Math.sqrt(i));
  }
}

const inst = new ExpensiveComputation();
console.log(inst.data[0]);  // computes once
console.log(inst.data[10]); // cached

Memoize

import { Memoize } from "performance-decorators/optimization";

class Calculator {
  @Memoize()
  fibonacci(n: number): number {
    if (n <= 1) return n;
    return this.fibonacci(n - 1) + this.fibonacci(n - 2);
  }
}

Throttle

import { Throttle } from "performance-decorators/optimization";

class ScrollHandler {
  @Throttle(100)
  onScroll(e: Event) {
    console.debug("Scroll event processed");
  }
}

πŸ“˜ API Documentation

All decorators include full JSDoc comments with parameter descriptions, return types, and usage examples. Inspect the source (src/debugging, src/optimizations) for details.

🚧 Contributing

Contributions, bug-reports, and ideas are welcome! Please open issues or pull requests, include tests for new features, and follow existing patterns.

πŸ“„ License

MIT License β€” see the LICENSE file for details.

About

Elevate your application's performance with πŸš€ Performance Decorators! This comprehensive TypeScript library offers powerful tools for performance monitoring and optimization, making it easier to track and resolve bottlenecks in both Node.js and browser environments.

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Packages

No packages published

Contributors 3

  •  
  •  
  •