如何以最简洁的方式对大量函数进行性能分析?
问题:批量函数性能分析的简洁实现方案
我需要对大量函数进行性能分析,希望实现方式尽可能简洁。
原函数示例:
export function foo( param1: string, param2?: Date | undefined, ) : string { if (param1 == "foo") return "foo"; return "bar" }
当前的实现方式需要手动拆分出fooImpl,还要重复写参数列表,非常繁琐:
export function foo( param1: string, param2?: Date | undefined, ) : string { const start = startFunction("foo"); // 记录函数开始时间 const result = fooImpl(param1, param2); endFunction(start); // 记录函数执行耗时 return result; } export function fooImpl( param1: string, param2?: Date | undefined, ) : string { if (param1 == "foo") return "foo"; return "bar" }
请问有什么更简洁的实现方案吗?
简洁实现方案
1. 高阶函数封装通用分析逻辑
写一个通用的高阶函数,自动包裹目标函数,无需手动拆分impl或重复参数列表:
// 通用性能分析高阶函数 function withPerformanceLogging<T extends (...args: any[]) => any>(func: T, funcName: string): T { return ((...args: Parameters<T>) => { const start = startFunction(funcName); const result = func(...args); endFunction(start); return result; }) as T; } // 原函数保持不变 function foo( param1: string, param2?: Date | undefined, ): string { if (param1 == "foo") return "foo"; return "bar"; } // 导出带性能分析的函数 export const fooWithLog = withPerformanceLogging(foo, "foo");
如果不需要保留原函数,甚至可以直接包裹定义:
export const foo = withPerformanceLogging( (param1: string, param2?: Date | undefined): string => { if (param1 == "foo") return "foo"; return "bar"; }, "foo" );
2. TypeScript装饰器(类方法场景)
如果函数是类的成员方法,用TS装饰器语法可以一行代码完成注入:
function PerformanceLog(target: any, propertyKey: string, descriptor: PropertyDescriptor) { const originalMethod = descriptor.value; descriptor.value = function(...args: any[]) { const start = startFunction(propertyKey); const result = originalMethod.apply(this, args); endFunction(start); return result; }; return descriptor; } class SomeClass { @PerformanceLog foo(param1: string, param2?: Date | undefined): string { if (param1 == "foo") return "foo"; return "bar"; } }
3. Proxy代理批量处理对象方法
如果函数是某个对象的属性,用Proxy可以批量给所有方法自动添加性能分析:
function createPerformanceProxiedObject<T extends object>(obj: T): T { return new Proxy(obj, { get(target, propKey) { const value = target[propKey as keyof T]; if (typeof value === "function") { return (...args: any[]) => { const start = startFunction(String(propKey)); const result = value.apply(target, args); endFunction(start); return result; }; } return value; } }); } // 示例:给对象的所有方法自动加性能分析 const obj = { foo(param1: string, param2?: Date | undefined): string { if (param1 == "foo") return "foo"; return "bar"; }, // 其他方法... }; const proxiedObj = createPerformanceProxiedObject(obj); // 调用proxiedObj.foo()时自动触发性能分析
内容的提问来源于stack exchange,提问作者jon
相关产品推荐
相关产品推荐

