【问题标题】:Reduce call stacks size in Javascript减少 Javascript 中的调用堆栈大小
【发布时间】: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


    【解决方案1】:

    要退出当前调用堆栈,一种选择是在 Promise.resolve 之后调用下一个方法 - 在其他同步 Javascript 处理完成后,它将作为微任务运行:

    a(){
        for(; this.index < this.data.length; this.index++){
            //some code
            if(someCondition) {
                Promise.resolve().then(() => {
                    this.processThisNext(this.b);
                });
                break;
            }else if(another condition){
                Promise.resolve().then(() => {
                    this.processThisNext(this.c);
                });
                break;
            }
        }
    }
    
    b(){
        for(; this.index < this.data.length; this.index++){
            //some code
            if(someCondition) {
                Promise.resolve().then(() => {
                    this.processThisNext(this.a);
                });
                break;
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-26
      • 2012-01-23
      • 2011-05-06
      • 2019-05-21
      • 1970-01-01
      • 2011-01-17
      • 2021-02-11
      • 2017-08-21
      相关资源
      最近更新 更多