Performance improvements.

Inspired by https://code.djangoproject.com/ticket/3202 with some additions.
Merge pull request #1 from dbrand666/1.5.1jirafe1

Performance improvements.