且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Javascript 中,即使从未抛出异常,使用 try-catch 块是否也很昂贵?

更新时间:2023-11-29 14:38:52

你在做典型的 CRUD UI 代码吗?使用 try catch,使用无缘无故地在代码中散布到 10000 的循环,地狱,使用 angular/ember - 你不会注意到任何性能问题.

Are you doing typical CRUD UI code? Use try catches, use loops that go to 10000 for no reason sprinkled in your code, hell, use angular/ember - you will not notice any performance issue.

如果你正在做低级库、物理模拟、游戏、服务器端等,那么从不抛出 try-catch 块通常根本不重要,但问题是 V8 在他们的优化编译器中不支持它直到引擎的版本 6,所以语法上包含 try catch 的整个包含函数将不会被优化.不过,您可以通过创建类似 tryCatch 的辅助函数来轻松解决此问题:

If you are doing low level library, physics simulations, games, server-side etc then the never throwing try-catch block wouldn't normally matter at all but the problem is that V8 didn't support it in their optimizing compiler until version 6 of the engine, so the entire containing function that syntactically contains a try catch will not be optimized. You can easily work around this though, by creating a helper function like tryCatch:

function tryCatch(fun) {
    try {
        return fun();
    }
    catch(e) {
        tryCatch.errorObj.e = e;
        return tryCatch.errorObj;
    }
}
tryCatch.errorObj = {e: null};


var result = tryCatch(someFunctionThatCouldThrow);
if(result === tryCatch.errorObj) {
    //The function threw
    var e = result.e;
}
else {
    //result is the returned value
}

在 V8 版本 6 之后(Node 8.3 和最新的 Chrome 附带),try-catch 内部代码的性能与普通代码相同.

After V8 version 6 (shipped with Node 8.3 and latest Chrome), the performance of code inside try-catch is the same as that of normal code.