Speed test: exists()
vs. get() + try/except
Test 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 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()
is over 10% faster for checking if an object has been saved in the database.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…