简体   繁体   English

在这种特定情况下,if-else 是否比 try-catch 更好,性能方面? 哪种方式是最佳实践?

[英]Is if-else better than try-catch in this particular scenario, performance wise? Which way is the best practice?

I've a json, I need to check a few values and perform a certain task, say this is my json,我有一个 json,我需要检查一些值并执行某个任务,说这是我的 json,

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

and the keys d,f and g might or might not be present, and if g == 1, I need to perform a certain task.并且键 d、f 和 g 可能存在也可能不存在,如果 g == 1,我需要执行某个任务。 So, which of the following gives me better performance.那么,以下哪一项给了我更好的表现。

if-else way of doing this if-else 这样做的方式

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

try-catch way of doing this尝试捕获这样做的方法

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

The thing with try-catch . try-catch的事情。 Is that it always attempts to get through the code inside the try , and if that doesn't work, it has to reroll everything inside the try back to the start of the try .是它总是试图通过内部的代码获得try ,如果还是不行,它必须重掷里面的一切try回到开始try
Only after rerolling, it'll enter the catch .只有在重新滚动后,它才会进入catch This makes using a try-catch much slower.这使得使用try-catch慢得多。
If there is instead a condition (like an if-else statement) at the start.如果在开头有一个条件(如 if-else 语句)。 And the statement is false, then it doesn't have to go through the if , or the rest of the if-statement at all.并且该语句为假,则它根本不必经过if或 if 语句的其余部分。

That's where it's more useful to use an if-else statement, and why you rather want the try-catch to be as short as needed.这就是使用if-else语句更有用if-else ,也是为什么您希望try-catch尽可能短的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM