Skip to content

Comment on JS performance: try / catch versus checking for undefined parent

Comments

On SpiderMonkey, a Javascript value is a 64-bit word. In most cases, 32 bits are set aside for the tag, and one possible tag is 'undefined value'. So checking to see if a value is undefined is basically a simple comparison, like checking if a pointer is NULL in C (except very slightly more work).

On the other hand, try/catch requires traversing some kind of structure to find the catch handler, and exceptions are often allocated somehow. This kind of action will need to inspect the stack, possibly look at the heap, and probably do many branches.

Plus, try/catch is not typically optimized for speed of catching exceptions. Exception handling is typically optimized so that the code path that doesn't throw an exception is almost as fast as it would be if the exception handling weren't there. You want people to use your exception handling so they can write more error-tolerant programs, but they might throw it out if it slows down their correct code. If you make sure you aren't slowing down the non-exception path, you may have to make tradeoffs that slow down the exception path.

The programming language shootout had a test of try/catch performance across languages. I remember Lisp was at the top, but not as if anyone cares -- try/catch performance isn't relevant to most programs.

OTOH, you may find it interesting that the reverse is true in Python. In Python, it is almost always faster to catch an exception rather than to check first. The way CPython checks for errors is by checking the return value of functions against NULL, after all, which is very fast. Checking ahead of time requires more Python code, and the Python code is going to be the slow part, at least on CPython.

That's true - how about repeating the test with valid code that DOESN'T throw an exception.

- Edit -

Just tried it, it's not even close (on FF4):

tryCatch with undef - ~55,000

ifCheck with undef - ~2,000,000

tryCatch with Object - ~100,000,000

ifCheck with Object - ~2,000,000

So if an error is not thrown the try/catch expression is WAY faster.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.