views:

299

answers:

3

is python exception slow? I'm kind using python exceptions to structure programm follow in my web application, and I'm wondering how throwing exceptions will affect performance of my application. what is your thoughts?

which one of the following statements is less expensive in terms of memory and cpu?

try:
    artist = Artist.objects.get(id=id)
except:
    raise Http404


artist = Artist.objects.filter(id=id)
if not artist:
    return HttpResponse('404')
+3  A: 

To really understand the performance of your system, you'll have to profile it. But Python is a language that encourages using exceptions like this, so they don't have an unusual overhead as they do in some other languages.

For example, sometimes people debate this choice:

if hasattr(obj, "attr"):
    use(obj.attr)
else:
    some_other(obj)

or:

try:
    use(obj.attr)
except AttributeError:
    some_other(obj)

The people who say you should use the first to avoid the exception need to understand that internally, hasattr is implemented by accessing the attribute and returning False if an AttributeError is raised. So in fact, both code chunks use exceptions.

Ned Batchelder
+1  A: 

This guy did a nice little writeup of testing try/except speed with dicts, I sure it would have some analogue in your case. Either way, doing a nice profile will give you the best info.

zdav
+10  A: 

Handling exceptions will be the least of your worries with regards to performance. I would suggest, however, that you use a shortcut provided by Django for you:

from django.shortcuts import get_object_or_404
artist = get_object_or_404(Artist, id=id)

Which either assigns the object to artist or returns a 404. It's win-win!

Also, you should check out the django-debug-toolbar, which provides rendering/cpu time, context switches, and all kinds of other helpful tidbits of data for developers and might be just the tool you need.

jathanism
this also uses exceptions right? I don't know how it is different from the method 1.
Mohamed
Yes it does but saves you from having to perform the logic yourself. It is identical to method 1 except that you used an `except` without an exception to match on, which means it would catch ANY exception (not good). Don't be scared of exceptions, they are a core part of how the language operates! You just need to make sure you are handling them wisely.
jathanism
+1 for "Handling exceptions will be the least of your worries with regards to performance."
celopes