Try… Catch Benchmark
The try...catch statement in JavaScript is a common tool, especially useful in a programming environment as volatile as the web.
Since I always try to make my scripts execute as quickly as possible, I was curious about the performance hit when using try...catch extensively.
Below is a benchmark testing three methods:
- A simple, bare-bones variable definition
- The same code, but with a
try...catchblock - The same code, but with a
try...catchblock and an intentional error
Here's the source code:
As you can see, each test is executed 10,000 times to get a good sampling of how long each is taking. Please note that this script could lock up your browser for a few moments (or even crash it), but you can run this benchmark yourself below:
Using Windows XP, I executed this script ten times using each of the common browsers, taking the averages and compiling them in the table below:
| Browser | Solo | With try...catch |
With try...catch and an error |
|---|---|---|---|
| Firefox 2 | 36 milliseconds | 47 milliseconds | 32.917 seconds |
| Firefox 3 | 3 milliseconds | 4 milliseconds | 156 milliseconds |
| Google Chrome | 0 milliseconds | 6 milliseconds | 69 milliseconds |
| Internet Explorer 6 | 33 milliseconds | 35 milliseconds | 209 milliseconds |
| Internet Explorer 7 | 33 milliseconds | 35 milliseconds | 178 milliseconds |
| Opera | 6 milliseconds | 10 milliseconds | 3.011 seconds |
| Safari 3 | 13 milliseconds | 16 milliseconds | 50 milliseconds |
Based on this benchmark, it appears that try...catch adds negligible overhead on its own;
it's the handling of errors that can add signifant execution time to your scripts.
Internet Explorer and Safari seem to handle errors very quickly, while Opera and especially Firefox could potentially completely ruin a user experience
(such as animation tweening) using this method. Be warned!
Edit 7/11/08: Added Firefox 3.
Edit 9/02/08: Added Google Chrome.
That is very insightful information. I myself never use try catch except where I have no control over possible exception and I expect them, this is very rare.
I’m not a fan of try/catch :)
I wonder why you didn’t include Firefox 3?
I ran it myself with FF3 three times and got:
Solo: 7ms
try…catch: 6ms
try.catch and an error: 19.882 seconds
Solo: 6ms
try…catch: 6ms
try.catch and an error: 19.806 seconds
Solo: 6ms
try…catch: 7ms
try.catch and an error: 19.782 seconds
Aside from the HORRIBLE performance catching an actual error, Firefox 3 beats all the rest.
Hi Robert,
To be honest I wrote this article before FF3 was out and only just recently published it. Thanks for reminding me! I will post an update (it needs to be on the same machine as the initial testing so the speeds remain relative).
Also World of Solitaire is great! All the YUI guys here love it.