【问题标题】:Is if-else better than try-catch in this particular scenario, performance wise? Which way is the best practice?在这种特定情况下,if-else 是否比 try-catch 更好,性能明智?哪种方式是最佳实践?
【发布时间】:2019-04-05 14:15:59
【问题描述】:

我有一个 json,我需要检查一些值并执行某个任务,比如说这是我的 json,

s = {
    "d": {
      "f": {
        "g": 1
      }
    }
  }

键 d,f 和 g 可能存在也可能不存在,如果 g == 1,我需要执行某个任务。那么,以下哪一项能给我带来更好的性能。

if-else 方法

if(s.d && s.d.f && s.d.f.g && s.d.f.g ==1)
{
    doSomeJob();
}
else
{
    doSomeOtherJob();
}

try-catch 方法

try{
if(s.d.f.g ==1)
{
    doSomeJob();
}
}catch(e){
    doSomeOtherJob();
}

【问题讨论】:

标签: javascript performance typescript if-statement try-catch


【解决方案1】:

try-catch 的东西。是不是它总是试图通过try 中的代码,如果这不起作用,它必须将try 中的所有内容重新滚动回try 的开头。
只有重新滚动后,它才会进入catch。这使得使用try-catch 慢得多。
如果在开始时有一个条件(如 if-else 语句)。并且该语句是错误的,那么它根本不需要通过if 或 if 语句的其余部分。

这就是使用if-else 语句更有用的地方,也是您希望try-catch 尽可能短的原因。

【讨论】:

  • s = 5; try{s = s+10; undefined['12']}catch(e){console.log(s)} 这段代码打印了 15,所以 try-catch 没有重新滚动在 try 块中执行的所有内容
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-04
  • 1970-01-01
  • 1970-01-01
  • 2017-06-30
  • 2023-03-14
  • 2017-11-04
  • 1970-01-01
相关资源
最近更新 更多