Django 中的 cached_property 与 Python 的函数工具有什么区别?
What is the difference between cached_property in Django vs. Python's functools?
Django 在标准库中有一个名为 cached_property
which can be imported from django.utils.functional
. On the other hand, Python 3.8 added cached_property
的装饰器,可以从 functools
.
导入
两者是否等价,即它们可以互换吗?或者两者有什么区别?何时使用其中一个或另一个有什么最佳实践吗?
经过一些研究,两者基本上以相同的方式工作,您会看到的唯一区别在于错误处理和性能。 Django 的问题跟踪器上有一个 ticket #30949 使用 functools.cached_property
而不是 django.utils.functional.cached_property
。
您可以在上面链接的票证中看到 source code [GitHub] for functools.cached_property
and also for django's version [GitHub]. The basic difference is functool's version does a little bit more error handling and the main difference is that functool uses locking mechanism for thread safety, this causes a performance dip compared to Django's version. From some benchmarking 完成,似乎 Django 的版本在性能方面效率更高:
% python benchmark.py
.....................
Django Cache: Mean +- std dev: 12.8 ms +- 0.2 ms
.....................
Python Cache: Mean +- std dev: 113 ms +- 2 ms
Python 的错误跟踪器上也有一个关于此的 issue 43468。
总而言之,如果线程安全不是问题,请使用 Django 版本,否则您可能需要使用 functools 版本。
Django 在标准库中有一个名为 cached_property
which can be imported from django.utils.functional
. On the other hand, Python 3.8 added cached_property
的装饰器,可以从 functools
.
两者是否等价,即它们可以互换吗?或者两者有什么区别?何时使用其中一个或另一个有什么最佳实践吗?
经过一些研究,两者基本上以相同的方式工作,您会看到的唯一区别在于错误处理和性能。 Django 的问题跟踪器上有一个 ticket #30949 使用 functools.cached_property
而不是 django.utils.functional.cached_property
。
您可以在上面链接的票证中看到 source code [GitHub] for functools.cached_property
and also for django's version [GitHub]. The basic difference is functool's version does a little bit more error handling and the main difference is that functool uses locking mechanism for thread safety, this causes a performance dip compared to Django's version. From some benchmarking 完成,似乎 Django 的版本在性能方面效率更高:
% python benchmark.py ..................... Django Cache: Mean +- std dev: 12.8 ms +- 0.2 ms ..................... Python Cache: Mean +- std dev: 113 ms +- 2 ms
Python 的错误跟踪器上也有一个关于此的 issue 43468。
总而言之,如果线程安全不是问题,请使用 Django 版本,否则您可能需要使用 functools 版本。