【发布时间】:2020-04-24 14:37:51
【问题描述】:
当我知道特定调用在函数中是最后一个并且我必须从函数中不返回任何内容时,我可以减少调用堆栈大小吗?
这是一个例子
constructor(){
this.processNext = this.a;
}
parse(stream){
stream.on('data', data => {
this.start(data);
})
}
start(data){
this.data += data;
//somecode
this.processNext();
}
a(){
for(; this.index < this.data.length; this.index++){
//some code
if(someCondition) {
this.processThisNext(this.b);
break;
}else if(another condition){
this.processThisNext(this.c);
break;
}
}
}
b(){
for(; this.index < this.data.length; this.index++){
//some code
if(someCondition) {
this.processThisNext(this.a);
break;
}
}
}
processThisNext(method){
this.processNext = method;
this.processNext();
}
c(){}
解释:
我将代码划分为多个函数,以减少比较次数并使其易于理解。我正在收听输入流的data 事件。 processNext 是一个代理函数,当data 事件被触发时,它总是被调用。 processNext 的值在逻辑中不断变化。
现在你可以在上面的代码中看到,当我调用processThisNext 时,我实际上想从当前函数调用中存在。此时,我不需要 this 和父函数出现在调用堆栈中。
有什么方法可以简化它吗?或通过其他方式减少调用堆栈?
【问题讨论】:
标签: node.js performance callstack