π 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.
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 (viaconsole.warnand optional handler) if execution time exceeds a threshold.LogNetworkRequests: Method decorator β Wrapsfetch()inside the decorated method scope and logs each request (method, URL, status, timing). Works ifglobalThis.fetchis available.LogReturnValue: Method decorator β Logs the returned value of a method (sync or async) using a supplied logger orconsole.log.
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.
npm install performance-decoratorsimport { LogExecutionTime } from "performance-decorators/debugging";
class PerformanceExample {
@LogExecutionTime()
quickMethod() {
// ...
}
@LogExecutionTime((ms, methodName) =>
console.debug(`[${methodName}] executed in ${ms.toFixed(2)}ms`)
)
detailedMethod() {
// ...
}
}import { LogMemoryUsage } from "performance-decorators/debugging";
class PerformanceExample {
@LogMemoryUsage()
methodWithMemoryUse() {
// ...
}
@LogMemoryUsage((deltaBytes, methodName) =>
console.debug(`[${methodName}] Ξ${deltaBytes} bytes`)
)
detailedMemoryMethod() {
// ...
}
}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");
}
}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 {
// ...
}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() {
// ...
}
}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();
}
}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();
}
}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();
}
}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 executesimport { 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]); // cachedimport { 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);
}
}import { Throttle } from "performance-decorators/optimization";
class ScrollHandler {
@Throttle(100)
onScroll(e: Event) {
console.debug("Scroll event processed");
}
}All decorators include full JSDoc comments with parameter descriptions, return types, and usage examples. Inspect the source (src/debugging, src/optimizations) for details.
Contributions, bug-reports, and ideas are welcome! Please open issues or pull requests, include tests for new features, and follow existing patterns.
MIT License β see the LICENSE file for details.