15

How time-intensive is the use of try/catch in JavaScript? I have an application and I am using it in a function which is called a few hundred times. Now I am afraid, that the try/catch statement is taking too much time and the application will take a lot longer than without it.

0

4 Answers 4

12

There are some nice tests on jsPref:

Conclusion: on the major browser, null to minimal differences.

Sign up to request clarification or add additional context in comments.

3 Comments

No difference IF the catch block is never entered. If it does it can cause huge performance issues b/c catch blocks are dynamic scope. Never use them for program logic, only for real unavoidable errors. yuiblog.com/assets/High_Perf_JavaScr_Ch2.pdf
Functions containing try and catch statements are inlined if an error is not thrown, otherwise if it is the method/function is then de-optimised.
The PDF linked above now 404s but can be found at web.archive.org/web/20111027151214/https://yuiblog.com/assets/…
7

You should take note of the following:

“The First Rule of Program Optimization: Don't do it. The Second Rule of Program Optimization (for experts only!): Don't do it yet.” - Michael A. Jackson

I've wasted time optimising sections of code that had little impact on performance. Make sure you know what is slow by running some timing experiments.

Comments

2

The try/catch clause creates a new scope in javascript, so every variable that has to come from the parent scope will be slightly slower.

The overhead isn't that great but too large to completely ignore for your inner loops.

Take a look at this video for a more in-depth explanation: http://www.youtube.com/watch?v=mHtdZgou0qU

4 Comments

It is not correct to say that a try block introduces new scope.
@Pointy: true, but I can't think of a better description right now. Do you have any suggestions?
I know what you're getting at but I'm pretty ignorant of sophisticated "language lawyer" terminology :-)
thx, nice site (especially that you can create your own test cases. The point most interesting for me was if a try-catch statement was much slower than the if statement . According to the tests it's about 25% slower. I have to see in the final application if this is acceptable.
1

In general, code executed inside a try block is expensive. But if you are invoking a try block on the order of a few hundred times, it's probably not an issue. If it were a few hundred thousand, you may want to re-think your design.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.