Performance improvements.

Inspired by https://code.djangoproject.com/ticket/3202 with some additions.