Created
October 7, 2025 10:53
-
-
Save joshnuss/93e71c7775be0f87da31620535ea9e8b to your computer and use it in GitHub Desktop.
Measure performance of functions with a Proxy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function perf<T extends object>(target: T, methods: string[]): T { | |
| return new Proxy(target, { | |
| get(target, key) { | |
| const item = Reflect.get(target, key) | |
| if (!methods.includes(key.toString())) { | |
| return item | |
| } | |
| return (...args: any[]) => { | |
| performance.mark(`start:${key.toString()}`) | |
| console.log(`Called ${key.toString()}() with ${args}`) | |
| const result = item.call(target, ...args) | |
| performance.mark(`end:${key.toString()}`) | |
| const measure = performance.measure(`start:${key.toString()}`, `end:${key.toString()}`) | |
| console.log(`${key.toString()}: ${measure.duration}ms`) | |
| return result | |
| } | |
| } | |
| }) | |
| } | |
| const object = { | |
| a: 1, | |
| b: 2, | |
| do_something(a: number, b: number, c: number) { | |
| console.log('hello world ' + [a,b,c]) | |
| let x = 0 | |
| // waste time | |
| for (let i=0; i< 10000000; i++) { | |
| x = i + 123 | |
| } | |
| } | |
| } | |
| const o = perf(object, ['do_something']) | |
| o.do_something(1,2,3) | |
| o.do_something(5,6,7) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment