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

查看:26
本文介绍了在 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 代码?使用尝试捕获,使用无缘无故地达到 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天全站免登陆