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')
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With