1

I am currently using try/catch to handle JSON.parse errors. But I have just recently found out after reading some best practices that using try/catch on nodejs has some performance overhead. Is the performance overhead fixed already and is there another way to avoid errors on JSON.parse without using try/catch?

Community
  • 1
  • 1
Gene Diaz
  • 536
  • 1
  • 7
  • 22
  • If you don't wrap `JSON.parse` in `try-catch`, it'll throw an Error into the wilderness - so you'll have to catch it somewhere else. So the technique shown in that answer is correct. – raina77ow Sep 05 '14 at 09:33
  • 1
    Related: http://programmers.stackexchange.com/questions/144326/try-catch-in-javascript-isnt-it-a-good-practice – raina77ow Sep 05 '14 at 09:34

2 Answers2

1

There is no simple way to avoid try-catch without your own parser.

Try this performance test: http://jsperf.com/try-catch-performance-overhead

Use Chrome for the test, since NodeJS is just V8. In my case there was a 41% performance penalty. However, unless you are going to reading thousands of JSONs per second, I suggest you just use the standard try-catch and make your code readable.

Note that for Firefox, there was virtually no difference between the 3 tests.

psiphi75
  • 1,985
  • 1
  • 24
  • 36
0

The problem with using try/catch constructions instead of callback error functions is that try/catch is NOT able to catch asynchronous events and may leak too much data when the exception is caught.

Best practice is to use try/catch at synchronous events:

try
{
  dangerous.function();
}
catch(error);
{
  console.log(error);
}

and a callback function for asynchronously fired events:

dangerous.function(function(error)
{
  console.log(error);
});
Placeholder
  • 4,651
  • 6
  • 33
  • 35