MST

星途 面试题库

面试题:JavaScript函数作为值时的优化实践 - 性能提升

在JavaScript中,我们经常会使用函数作为回调来处理异步操作,比如在`setTimeout`或`Promise`中。假设有一系列连续的异步操作,每个操作都依赖前一个操作的结果,并且每个操作都用函数作为值来定义。请描述一种优化方式,减少不必要的函数创建和内存开销,同时提高代码的执行效率。请用代码示例说明。
24.2万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
  1. 使用函数引用而非匿名函数
    • 当一系列异步操作依赖前一个操作的结果时,我们可以定义具名函数,然后通过函数引用传递给异步操作,而不是每次都创建新的匿名函数。
    • 示例代码如下:
// 定义具名函数
function step1() {
    return new Promise((resolve) => {
        setTimeout(() => {
            console.log('Step 1 completed');
            resolve('Result of step 1');
        }, 1000);
    });
}

function step2(resultFromStep1) {
    return new Promise((resolve) => {
        setTimeout(() => {
            console.log('Step 2 completed with result:', resultFromStep1);
            resolve('Result of step 2');
        }, 1000);
    });
}

function step3(resultFromStep2) {
    return new Promise((resolve) => {
        setTimeout(() => {
            console.log('Step 3 completed with result:', resultFromStep2);
            resolve('Final result');
        }, 1000);
    });
}

// 链式调用
step1()
   .then(step2)
   .then(step3)
   .then((finalResult) => {
        console.log('Final result:', finalResult);
    });
  1. 复用函数逻辑
    • 如果某些步骤的逻辑有相似性,可以进一步优化。例如,如果step2step3除了日志输出外,处理数据的逻辑相同,可以复用函数逻辑。
    • 示例代码如下:
function commonStep(result) {
    return new Promise((resolve) => {
        setTimeout(() => {
            console.log('Step completed with result:', result);
            resolve(result + ' processed');
        }, 1000);
    });
}

function step1() {
    return new Promise((resolve) => {
        setTimeout(() => {
            console.log('Step 1 completed');
            resolve('Result of step 1');
        }, 1000);
    });
}

// 链式调用
step1()
   .then(commonStep)
   .then(commonStep)
   .then((finalResult) => {
        console.log('Final result:', finalResult);
    });

通过这种方式,我们减少了不必要的函数创建,提高了代码的执行效率,同时也提高了代码的可维护性。