NodeJS:抛出错误仍然会带来性能损失吗?

SIL*_*ENT 6 javascript exception try-catch throw node.js

根据nodejs框架的不同,通常有两种方法来管理错误。

  • 扔掉它们(即throw new Error('invalid id');
  • 返回它们(即return { 400: 'invalid id' };

由于旧的建议是抛出错误效率低下,我总是尝试返回错误,但我更喜欢抛出错误,因为它们更方便。唯一一篇提到性能影响的文章是 Node v0.1。

这仍然是真的吗?


更新1

Nvm,我意识到我可以自己测试一下。以下代码供参考:

import { performance } from "perf_hooks";

function ThrowException() {
    throw new Error("invalid exception");
}
const _ATTEMPT = 1000000;
function ThrowingExceptions() {
    const p1 = performance.now();
    for (let i = 0; i < _ATTEMPT; i++) {
        try {
            ThrowException();
        } catch (ex: any) {
            // log error
        }
    }
    const p2 = performance.now();
    console.log(`ThrowingExceptions: ${p2 - p1}`);
}
function ReturnException() {
    return { error: { _: "invalid exception" } };
}
function ReturningExceptions() {
    const p1 = performance.now();
    for (let i = 0; i < _ATTEMPT; i++) {
        const ex = ReturnException();
        if (ex.error) {
            // log error
        }
    }
    const p2 = performance.now();
    console.log(`ReturningExceptions: ${p2 - p1}`);
}

function Process() {
    ThrowingExceptions();
    ReturningExceptions();
    ThrowingExceptions();
    ReturningExceptions();
}

Process();
Run Code Online (Sandbox Code Playgroud)

结果

ThrowingExceptions: 15961.33209991455
ReturningExceptions: 5.09220027923584
ThrowingExceptions: 16461.43380022049
ReturningExceptions: 3.0963997840881348
Run Code Online (Sandbox Code Playgroud)

更新2

制造错误会造成最大的惩罚。谢谢@Bergi

import { performance } from "perf_hooks";

const error = new Error("invalid exception");
function ThrowException() {
    throw error;
}
const _ATTEMPT = 1000000;
function ThrowingExceptions() {
    const p1 = performance.now();
    for (let i = 0; i < _ATTEMPT; i++) {
        try {
            ThrowException();
        } catch (ex: any) {
            // log error
        }
    }
    const p2 = performance.now();
    console.log(`ThrowingExceptions: ${p2 - p1}`);
}
function ReturnException() {
    return { error };
}
function ReturningExceptions() {
    const p1 = performance.now();
    for (let i = 0; i < _ATTEMPT; i++) {
        const ex = ReturnException();
        if (ex.error) {
            // log error
        }
    }
    const p2 = performance.now();
    console.log(`ReturningExceptions: ${p2 - p1}`);
}

function Process() {
    ThrowingExceptions();
    ReturningExceptions();
    ThrowingExceptions();
    ReturningExceptions();
}

Process();
Run Code Online (Sandbox Code Playgroud)

结果

ThrowingExceptions: 2897.1585998535156
ReturningExceptions: 3.7821998596191406
ThrowingExceptions: 2905.3162999153137
ReturningExceptions: 4.0701003074646
Run Code Online (Sandbox Code Playgroud)