DEV Community

Discussion on: Dead Simple Python: Errors

Collapse
 
sandordargo profile image
Sandor Dargo

Thanks for the article. As I'm coming from the C++ world, I'm suspicious when people say that try-except blocks are not so expensive.

And that's true, relatively they are not as expensive as in C++.

But have you actually measured, for example, the cost of an extra key check in a dictionary lookup compared to raising an exception?

This would vary from machine to machine, I guess, but on mine, the failure case is 30-40x slower with the try-raise block compared to the if-else. That is quite significant.

On the other hand, the success case is about 30-50% faster with the try-case block.

30-50% compared to 3000-4000%.

To me, the bottom line is, if performance matters, measure and know your data. Otherwise, you might just mess things up.

Collapse
 
codemouse92 profile image
Jason C. McDonald • Edited

It's a good point - you should always measure for your specific scenario.

The except is supposed to be the "exceptional" scenario, rather than the rule. In general, the try should succeed several times more often than it fails. Contrast that with the if...else (ask permission) scenario, where we perform the lookup every time, the try...except scenario actually winds up being the more efficient approach in most cases. (See this StackOverflow answer.)

To put that another way, if you imagine that just the if...else and try...except structures by themselves are roughly identical in performance, at least typical scenarios, it is the conditional statement inside of the if() that is the point of inefficiency.

I'm oversimplifying, of course, but this can at least get you in the ballpark. if(i % 2 == 0) is going to be pretty inexpensive, and would succeed only 50% of the time in any given sequential, so that would be a case where we'd almost certainly use an if...else for our flow control; try...except would be too expensive anyway! By contrast, the dictionary lookup is quite a bit more expensive, especially if it succeeds eight times more than it fails. If we know from our data that it will fail more than succeed, however, an "ask permission" approach may indeed be superior.

At any rate, yes, measure, and consider the costs of your particular scenario.

P.S. As I mentioned in the article, of course, the collections.defaultdict would be considered superior to both try...except and if...else in the example scenario.