[英]Javascript Proxy: detect recursions
I want to create a simple performance logger: 我想创建一个简单的性能记录器:
function makePerformanceMeasured(target) {
return new Proxy(target, {
apply: (target, thisArg, args) => {
if(!target.name) {
throw 'The function must have a name'
}
console.time(target.name);
const result = target.apply(thisArg, args);
console.timeEnd(target.name);
return result;
}
})
}
for non-recursional functions - all works well: 对于非递归函数 - 一切正常:
function isPrime(n) {
if(n < 2) {
return false;
}
for(var i = 0; i < n; i++) {
if(n % i === 0) {
return false;
}
}
return true;
}
isPrime = makePerformanceMeasured(isPrime);
isPrime(100); // 0.001ms false
But with recursional functions: 但是使用递归函数:
function fact(n) {
if(n < 2) {
return 1;
}
return n * fact(n - 1);
}
fact = makePerformanceMeasured(fact);
fact(4);
// 0.025ms
// 0ms
// 0ms
// 24
I want to detect in the Proxy apply
trap - if the function has been called recursively - make time measurements only for first function call in the stack. 我想在Proxy apply
trap中检测 - 如果函数是递归调用的 - 只对堆栈中的第一个函数调用进行时间测量。 Thanks! 谢谢!
You can set a flag to remember whether you're already inside a call: 你可以设置一个标志来记住你是否已经在通话中:
function makePerformanceMeasured(target) {
var isCalled = false;
return new Proxy(target, {
apply: (target, thisArg, args) => {
if (!isCalled) {
console.time(target.name);
isCalled = true;
const result = Reflect.apply(target, thisArg, args);
isCalled = false;
console.timeEnd(target.name);
return result;
} else {
return Reflect.apply(target, thisArg, args);
}
}
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.