Speed ββtest: exists()
vs get() + try/except
Tested functions in test.py :
from testapp.models import User def exists(x): return User.objects.filter(pk=x).exists() def get(x): try: User.objects.get(pk=x) return True except User.DoesNotExist: return False
Using timeit in the shell:
In [1]: from testapp import test In [2]: %timeit for x in range(100): test.exists(x) 10 loops, best of 3: 88.4 ms per loop In [3]: %timeit for x in range(100): test.get(x) 10 loops, best of 3: 105 ms per loop In [4]: timeit for x in range(1000): test.exists(x) 1 loops, best of 3: 880 ms per loop In [5]: timeit for x in range(1000): test.get(x) 1 loops, best of 3: 1.02 s per loop
Conclusion : exists()
over 10% faster to check if an object is stored in the database.
source share