an0nym0use
an0nym0use

Reputation: 341

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,

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. So, which of the following gives me better performance.

if-else way of doing this

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();
}

Upvotes: 1

Views: 99

Answers (1)

Steven
Steven

Reputation: 2123

The thing with 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.
Only after rerolling, it'll enter the catch. This makes using a try-catch much slower.
If there is instead a condition (like an if-else statement) at the start. And the statement is false, then it doesn't have to go through the if, or the rest of the if-statement at all.

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.

Upvotes: 1

Related Questions