1

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();
}
an0nym0use
  • 311
  • 1
  • 4
  • 8
  • 3
    `try` - `catch` is almost never going to perform better than simple tests. Some optimizing runtimes will not even attempt to optimize functions with exception handlers. However in most cases it won't make a significant difference to the way your program works. – Pointy Apr 05 '19 at 14:17
  • I am also with understanding that try/catch blocks are more expensive than if/else statements – Isaac Vidrine Apr 05 '19 at 14:17
  • 2
    Compare them on https://jsperf.com/ – adiga Apr 05 '19 at 14:18
  • https://www.oreilly.com/library/view/high-performance-javascript/9781449382308/ch04.html – Dupocas Apr 05 '19 at 14:52
  • Possible duplicate of [Case vs If Else If: Which is more efficient?](https://stackoverflow.com/questions/2158759/case-vs-if-else-if-which-is-more-efficient) – Dupocas Apr 05 '19 at 14:53

1 Answers1

1

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.

Steven
  • 1,996
  • 3
  • 22
  • 33
  • `s = 5; try{s = s+10; undefined['12']}catch(e){console.log(s)}` This piece of code printed 15, so try-catch was not rerolling everything executed in the try block – an0nym0use Apr 26 '19 at 15:04