Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How slow are Python/django exceptions?

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')
like image 647
Mohamed Avatar asked Dec 11 '09 01:12

Mohamed


2 Answers

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.

like image 119
jathanism Avatar answered Sep 24 '22 15:09

jathanism


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.

like image 37
Ned Batchelder Avatar answered Sep 24 '22 15:09

Ned Batchelder