Speed test: `exists()` vs. `get() + try/except
iSTEP Lv2

From Try2Explore.com by Abraham

问题描述

I’m writing tests for a django application and I want to check if an object has been saved to the database. Which is the most efficient/correct way to do it?

1
User.objects.filter(username=testusername).exists()

or

1
2
3
try:
User.objects.get(username=testusername)
except User.DoesNotExist:

解决方案

Speed test: exists() vs get() + try/except

Test functions in test.py:

1
2
3
4
5
6
7
8
9
10
11
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:

1
2
3
4
5
6
7
8
9
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.

说明

在只要求判断数据库是否存在某条数据的情况,使用 exists()有更高的效率。

在需要获得实例并作检查等情况下,get() + try/except有着更广的应用场景。

  • 本文标题:Speed test: `exists()` vs. `get() + try/except
  • 本文作者:iSTEP
  • 创建时间:2021-08-07 21:54:53
  • 本文链接:https://istep.github.io/2021/08/07/Speed-test-exists-vs-get-try-except/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
 评论