1

Possible Duplicate:
Try/catch or validation for speed?

I just started learning Python. I have a question about exception handling mostly because I don't know what exactly happens behind the scene on each exception:

  1. What is the performance penalty of using exception handling?
  2. Is it a good practice to use exception handling tricks in a performance code?

From trick I mean something like this code:

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

This code very frequently triggers exceptions.

Community
  • 1
  • 1
Kamyar Souri
  • 1,871
  • 19
  • 29
  • I asked a similar question recently: [Try/catch or validation for speed?](http://stackoverflow.com/questions/5589532/try-catch-or-validation-for-speed). – Blender Dec 15 '11 at 00:29
  • In C++ exception handling introduces an overhead for just being present and when triggered tends to cause a large performance hit compared to validation. Though I'm not real sure how well this maps to Python being as python is generally interpreted. Here is an article: (http://www.jacopretorius.net/2009/10/exceptions-should-be-exceptional.html ) that talks about this question in depths as related to C#. (My original comment stated the article was related to C++, but this particular one talks about .NET and C#. There are articles that cover the same topic for C++). Should I make this an answer? – nixeagle Dec 15 '11 at 00:33
  • i don't think C++ or C# is relevant to this discussion -- python is too different in the way it works. in fact, I suspect (though I'm not sure) that precisely the opposite is true in python. – simon Dec 15 '11 at 00:56
  • 1
    A while ago I asked a (somewhat) similar question. http://stackoverflow.com/questions/3111195/python-performance-try-except-or-not-in I have since learned that I probably shouldn't be worried about this until I know I should be worried about it. `timeit` and `cProfile` are your friends. – Wilduck Dec 15 '11 at 00:56
  • @nixeagle: Python is a very different beast. C++ experience with minor performance tweaks like this doesn't carry over very well. –  Dec 15 '11 at 00:58
  • @Hurkyl ah, thanks! I know enough python to be dangerous ;) and thought ISO C++ or microsoft's C# performance with respect to python would be a good approximation. Apparently not! Anyway I upvoted this question so hopefully someone with a clue and an answer will stop in soon ;). – nixeagle Dec 15 '11 at 01:00

0 Answers0