在 Javascript 中,即使从未抛出异常,使用 try-catch 块是否也很昂贵? [英] In Javascript, is it expensive to use try-catch blocks even if an exception is never thrown?

查看:28
本文介绍了在 Javascript 中,即使从未抛出异常,使用 try-catch 块是否也很昂贵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当没有抛出异常时,使用多个 try-catch 块是否慢"?我的问题与 这个,但用于 JavaScript.

Is it "slow" to use several try-catch blocks when no exceptions are thrown in any of them? My question is the same as this one, but for JavaScript.

假设我有 20 个函数,其中包含 try-catch 块,另一个函数调用这 20 个函数中的每一个它们都没有抛出异常.我的代码会因为这个 try-catch 块而执行得更慢或更差吗?

Suppose I have 20 functions which have try-catch blocks in them and another function that calls every one of those 20 functions where none of them throw an exception. Will my code execute slower or perform much worse because of this try-catch blocks?

推荐答案

你在做典型的 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.

这篇关于在 Javascript 中,即使从未抛出异常,使用 try-catch 块是否也很昂贵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆