Optimize Last is Wrong, Sort Of

One of the methodologies of Extreme Programming is to code first and optimize last. While I can understand where this is coming from I don’t necessarily agree with it, or at least not always. The truth is, there are some cases where quickly optimizing can help you out a lot, especially in the long run.

Optimizing Database Queries

When using a framework that includes a ORM (Object-Relational Mapper) it is sometimes easy to forget exactly what is happening under the hood. It also always for you to write code that’ll have excessive database queries and joins. Code like the following can easily and quickly be optimized, sometimes reducing the number of queries from a few hundred down to a couple.

#models.py
class Comment(models.Model):
    user = models.ForeignKey(User)
    comment = models.TextField()
 
#views.py
#Hits the database once
comments = Comment.objects.all()
for comment in comments:
    #Hits the database each iteration
    print comment.user.email
 
#Hits the database once
comments = Comment.objects.select_related().all()
for comment in comments:
    #Doesn't hit the database because comment.user has already been prepopulated
    print comment.user.email

I realize this is an over simplified example but if you have a lot of comments, using select_related() could greatly decrease the number of database queries you have to do. As a side note `select_related()` can be very painful on large datasets. In this case using `.raw(QUERY)` is a better solution.

Minifying and Combining CSS & Javascript Files
When a person comes to your web application their browser needs to download (unless it’s cached) all the resources necessary to properly display the content. For every CSS file and Javascript file you have included it needs to send off a request to get it. While this may not seem like a big deal if you have a lot of files or they’re on a slow connection this can take a long time.

Using applications like django-compress or django-compressor will help you minify and combine your CSS and Javascript files automatically.

Change Webservers
One final optimization practice that you can quickly implement is to use faster web servers. By default almost everyone uses Apache because it’s pre-installed and the tutorials out there are abundant.

An easy way to speed of your application (by a lot) and use a lot less memory is to stop using Apache and use Nginx and Gunicorn (or some other WSGI webserver). This will not only use less memory but it’ll also speed up your requests.

Final Thoughts
Here are only a few ways where you can quickly optimize your code/practices as you develop that will greatly enhance performance. While you don’t want to spend a lot of time optimizing, sometimes taking the few minutes to assess things you could optimize can save you a lot down the road.