{"title":"性能和优化","version":"2.0","locale":"zh-hans","docname":"topics/performance","url":"/zh-hans/2.0/topics/performance/","canonical":"https://djangodocs.dev/zh-hans/2.0/topics/performance/","summary":"本文档概述了一些技术和工具，这些技术和工具可以帮助您更有效地运行Django代码——更快，并且使用更少的系统资源。","html":"<h1>性能和优化<a class=\"heading-anchor\" href=\"#performance-and-optimization\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h1>\n<p>本文档概述了一些技术和工具，这些技术和工具可以帮助您更有效地运行Django代码——更快，并且使用更少的系统资源。</p>\n<section id=\"introduction\">\n<h2>介绍<a class=\"heading-anchor\" href=\"#introduction\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>通常，首先要考虑的是编写*工作的*代码，它的逻辑功能与产生预期输出所需的逻辑功能相同。然而，有时，这并不足以使代码像人们所希望的那样*高效地*工作。</p>\n<p>在这种情况下，需要的是一些东西——在实践中，通常是一组东西——以提高代码的性能，而不影响或只影响其行为。</p>\n</section>\n<section id=\"general-approaches\">\n<h2>一般方法<a class=\"heading-anchor\" href=\"#general-approaches\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<section id=\"what-are-you-optimizing-for\">\n<h3>你在*为*什么而优化？<a class=\"heading-anchor\" href=\"#what-are-you-optimizing-for\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>清楚地理解你所说的“绩效”是什么很重要，因为它不仅仅是一个指标。</p>\n<p>提高速度可能是程序最明显的目标，但有时可能会寻求其他性能改进，例如降低内存消耗或减少对数据库或网络的要求。</p>\n<p>一个领域的改进通常会提高另一个领域的性能，但并不总是如此；有时甚至会牺牲另一个领域的性能。例如，一个程序速度的提高可能会导致它使用更多的内存。更糟糕的是，如果速度提高太过内存不足，以致于系统开始耗尽内存，那么你所做的弊大于利。</p>\n<p>还有其他的权衡。你自己的时间是一个宝贵的资源，比CPU时间更宝贵。一些改进可能太难实现，或者可能影响代码的可移植性或可维护性。并非所有的性能改进都值得付出努力。</p>\n<p>所以，你需要知道你的目标是什么样的性能改进，你也需要知道你有一个很好的理由去瞄准那个方向——而且你需要：</p>\n</section>\n<section id=\"performance-benchmarking\">\n<h3>性能标竿<a class=\"heading-anchor\" href=\"#performance-benchmarking\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>仅仅猜测或假设代码中存在效率低下的原因是没有好处的。</p>\n<section id=\"django-tools\">\n<h4>Django工具<a class=\"heading-anchor\" href=\"#django-tools\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p><a href=\"#id1\"><span class=\"problematic\" id=\"id2\">`</span></a>django-debug-toolbar &lt;<a class=\"reference external\" href=\"https://github.com/jazzband/django-debug-toolbar/\">https://github.com/jazzband/django-debug-toolbar/</a>&gt;`_是一个非常方便的工具，它可以深入了解您的代码正在做什么以及花费了多少时间。特别是它可以显示您的页面生成的所有SQL查询，以及每个查询所用的时间。</p>\n<p>第三方面板也可用于工具栏，可以（例如）报告缓存性能和模板呈现时间。</p>\n</section>\n<section id=\"third-party-services\">\n<h4>第三方服务<a class=\"heading-anchor\" href=\"#third-party-services\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>There are a number of free services that will analyze and report on the\nperformance of your site's pages from the perspective of a remote HTTP client,\nin effect simulating the experience of an actual user.</p>\n<p>These can't report on the internals of your code, but can provide a useful\ninsight into your site's overall performance, including aspects that can't be\nadequately measured from within Django environment. Examples include:</p>\n<ul class=\"simple\">\n<li><p><a class=\"reference external\" href=\"http://yslow.org/\">Yahoo's Yslow</a></p></li>\n<li><p><a class=\"reference external\" href=\"https://developers.google.com/speed/pagespeed/\">Google PageSpeed</a></p></li>\n</ul>\n<p>There are also several paid-for services that perform a similar analysis,\nincluding some that are Django-aware and can integrate with your codebase to\nprofile its performance far more comprehensively.</p>\n</section>\n</section>\n<section id=\"get-things-right-from-the-start\">\n<h3>Get things right from the start<a class=\"heading-anchor\" href=\"#get-things-right-from-the-start\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Some work in optimization involves tackling performance shortcomings, but some\nof the work can simply be built in to what you'd do anyway, as part of the good\npractices you should adopt even before you start thinking about improving\nperformance.</p>\n<p>In this respect Python is an excellent language to work with, because solutions\nthat look elegant and feel right usually are the best performing ones. As with\nmost skills, learning what &quot;looks right&quot; takes practice, but one of the most\nuseful guidelines is:</p>\n<section id=\"work-at-the-appropriate-level\">\n<h4>Work at the appropriate level<a class=\"heading-anchor\" href=\"#work-at-the-appropriate-level\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>Django offers many different ways of approaching things, but just because it's\npossible to do something in a certain way doesn't mean that it's the most\nappropriate way to do it. For example, you might find that you could calculate\nthe same thing - the number of items in a collection, perhaps - in a\n<code class=\"docutils literal notranslate\">QuerySet</code>, in Python, or in a template.</p>\n<p>However, it will almost always be faster to do this work at lower rather than\nhigher levels. At higher levels the system has to deal with objects through\nmultiple levels of abstraction and layers of machinery.</p>\n<p>That is, the database can typically do things faster than Python can, which can\ndo them faster than the template language can:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"c1\"># QuerySet operation on the database</span>\n<span class=\"c1\"># fast, because that&#39;s what databases are good at</span>\nmy_bicycles<span class=\"o\">.</span>count<span class=\"p\">()</span>\n\n<span class=\"c1\"># counting Python objects</span>\n<span class=\"c1\"># slower, because it requires a database query anyway, and processing</span>\n<span class=\"c1\"># of the Python objects</span>\n<span class=\"nb\">len</span><span class=\"p\">(</span>my_bicycles<span class=\"p\">)</span>\n\n<span class=\"c1\"># Django template filter</span>\n<span class=\"c1\"># slower still, because it will have to count them in Python anyway,</span>\n<span class=\"c1\"># and because of template language overheads</span>\n<span class=\"p\">{{</span> my_bicycles<span class=\"o\">|</span>length <span class=\"p\">}}</span>\n</code></pre></div>\n<p>Generally speaking, the most appropriate level for the job is the lowest-level\none that it is comfortable to code for.</p>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">Note</p>\n<p>The example above is merely illustrative.</p>\n<p>Firstly, in a real-life case you need to consider what is happening before\nand after your count to work out what's an optimal way of doing it <em>in that\nparticular context</em>. The database optimization documents describes <a class=\"reference internal\" href=\"/zh-hans/2.0/topics/db/optimization/#overuse-of-count-and-exists\"><span class=\"std std-ref\">a\ncase where counting in the template would be better</span></a>.</p>\n<p>Secondly, there are other options to consider: in a real-life case, <code class=\"docutils literal notranslate\">{{\nmy_bicycles.count }}</code>, which invokes the <code class=\"docutils literal notranslate\">QuerySet</code> <code class=\"docutils literal notranslate\">count()</code> method\ndirectly from the template, might be the most appropriate choice.</p>\n</aside>\n</section>\n</section>\n</section>\n<section id=\"caching\">\n<h2>Caching<a class=\"heading-anchor\" href=\"#caching\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Often it is expensive (that is, resource-hungry and slow) to compute a value,\nso there can be huge benefit in saving the value to a quickly accessible cache,\nready for the next time it's required.</p>\n<p>It's a sufficiently significant and powerful technique that Django includes a\ncomprehensive caching framework, as well as other smaller pieces of caching\nfunctionality.</p>\n<section id=\"the-caching-framework\">\n<h3><a class=\"reference internal\" href=\"/zh-hans/2.0/topics/cache/\"><span class=\"doc\">The caching framework</span></a><a class=\"heading-anchor\" href=\"#the-caching-framework\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Django's <a class=\"reference internal\" href=\"/zh-hans/2.0/topics/cache/\"><span class=\"doc\">caching framework</span></a> offers very significant\nopportunities for performance gains, by saving dynamic content so that it\ndoesn't need to be calculated for each request.</p>\n<p>For convenience, Django offers different levels of cache granularity: you can\ncache the output of specific views, or only the pieces that are difficult to\nproduce, or even an entire site.</p>\n<p>Implementing caching should not be regarded as an alternative to improving code\nthat's performing poorly because it has been written badly. It's one of the\nfinal steps towards producing well-performing code, not a shortcut.</p>\n</section>\n<section id=\"cached-property\">\n<h3><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/utils/#django.utils.functional.cached_property\" title=\"django.utils.functional.cached_property\"><code class=\"xref py py-class docutils literal notranslate\">cached_property</code></a><a class=\"heading-anchor\" href=\"#cached-property\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>It's common to have to call a class instance's method more than once. If\nthat function is expensive, then doing so can be wasteful.</p>\n<p>Using the <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/utils/#django.utils.functional.cached_property\" title=\"django.utils.functional.cached_property\"><code class=\"xref py py-class docutils literal notranslate\">cached_property</code></a> decorator saves the\nvalue returned by a property; the next time the function is called on that\ninstance, it will return the saved value rather than re-computing it. Note that\nthis only works on methods that take <code class=\"docutils literal notranslate\">self</code> as their only argument and that\nit changes the method to a property.</p>\n<p>Certain Django components also have their own caching functionality; these are\ndiscussed below in the sections related to those components.</p>\n</section>\n</section>\n<section id=\"understanding-laziness\">\n<h2>Understanding laziness<a class=\"heading-anchor\" href=\"#understanding-laziness\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p><em>Laziness</em> is a strategy complementary to caching. Caching avoids\nrecomputation by saving results; laziness delays computation until it's\nactually required.</p>\n<p>Laziness allows us to refer to things before they are instantiated, or even\nbefore it's possible to instantiate them. This has numerous uses.</p>\n<p>For example, <a class=\"reference internal\" href=\"/zh-hans/2.0/topics/i18n/translation/#lazy-translations\"><span class=\"std std-ref\">lazy translation</span></a> can be used before the\ntarget language is even known, because it doesn't take place until the\ntranslated string is actually required, such as in a rendered template.</p>\n<p>Laziness is also a way to save effort by trying to avoid work in the first\nplace. That is, one aspect of laziness is not doing anything until it has to be\ndone, because it may not turn out to be necessary after all. Laziness can\ntherefore have performance implications, and the more expensive the work\nconcerned, the more there is to gain through laziness.</p>\n<p>Python provides a number of tools for lazy evaluation, particularly through the\n<a class=\"reference external\" href=\"https://docs.python.org/3/glossary.html#term-generator\" title=\"(in Python v3.14)\"><span class=\"xref std std-term\">generator</span></a> and <a class=\"reference external\" href=\"https://docs.python.org/3/glossary.html#term-generator-expression\" title=\"(in Python v3.14)\"><span class=\"xref std std-term\">generator expression</span></a> constructs. It's worth\nreading up on laziness in Python to discover opportunities for making use of\nlazy patterns in your code.</p>\n<section id=\"laziness-in-django\">\n<h3>Laziness in Django<a class=\"heading-anchor\" href=\"#laziness-in-django\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Django is itself quite lazy. A good example of this can be found in the\nevaluation of <code class=\"docutils literal notranslate\">QuerySets</code>. <a class=\"reference internal\" href=\"/zh-hans/2.0/topics/db/queries/#querysets-are-lazy\"><span class=\"std std-ref\">QuerySets are lazy</span></a>.\nThus a <code class=\"docutils literal notranslate\">QuerySet</code> can be created, passed around and combined with other\n<code class=\"docutils literal notranslate\">QuerySets</code>, without actually incurring any trips to the database to fetch\nthe items it describes. What gets passed around is the <code class=\"docutils literal notranslate\">QuerySet</code> object, not\nthe collection of items that - eventually - will be required from the database.</p>\n<p>On the other hand, <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/models/querysets/#when-querysets-are-evaluated\"><span class=\"std std-ref\">certain operations will force the evaluation of a\nQuerySet</span></a>. Avoiding the premature evaluation of\na <code class=\"docutils literal notranslate\">QuerySet</code> can save making an expensive and unnecessary trip to the\ndatabase.</p>\n<p>Django also offers a <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/utils/#django.utils.functional.keep_lazy\" title=\"django.utils.functional.keep_lazy\"><code class=\"xref py py-meth docutils literal notranslate\">keep_lazy()</code></a> decorator.\nThis allows a function that has been called with a lazy argument to behave\nlazily itself, only being evaluated when it needs to be. Thus the lazy argument\n- which could be an expensive one - will not be called upon for evaluation\nuntil it's strictly required.</p>\n</section>\n</section>\n<section id=\"databases\">\n<h2>Databases<a class=\"heading-anchor\" href=\"#databases\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<section id=\"database-optimization\">\n<h3>Database optimization<a class=\"heading-anchor\" href=\"#database-optimization\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Django's database layer provides various ways to help developers get the best\nperformance from their databases. The <a class=\"reference internal\" href=\"/zh-hans/2.0/topics/db/optimization/\"><span class=\"doc\">database optimization documentation</span></a> gathers together links to the relevant\ndocumentation and adds various tips that outline the steps to take when\nattempting to optimize your database usage.</p>\n</section>\n<section id=\"other-database-related-tips\">\n<h3>Other database-related tips<a class=\"heading-anchor\" href=\"#other-database-related-tips\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Enabling <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/databases/#persistent-database-connections\"><span class=\"std std-ref\">Persistent connections</span></a> can speed up connections to the\ndatabase accounts for a significant part of the request processing time.</p>\n<p>This helps a lot on virtualized hosts with limited network performance, for example.</p>\n</section>\n</section>\n<section id=\"http-performance\">\n<h2>HTTP performance<a class=\"heading-anchor\" href=\"#http-performance\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<section id=\"middleware\">\n<h3>中间件<a class=\"heading-anchor\" href=\"#middleware\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Django comes with a few helpful pieces of <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/middleware/\"><span class=\"doc\">middleware</span></a>\nthat can help optimize your site's performance. They include:</p>\n<section id=\"conditionalgetmiddleware\">\n<h4><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/middleware/#django.middleware.http.ConditionalGetMiddleware\" title=\"django.middleware.http.ConditionalGetMiddleware\"><code class=\"xref py py-class docutils literal notranslate\">ConditionalGetMiddleware</code></a><a class=\"heading-anchor\" href=\"#conditionalgetmiddleware\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>Adds support for modern browsers to conditionally GET responses based on the\n<code class=\"docutils literal notranslate\">ETag</code> and <code class=\"docutils literal notranslate\">Last-Modified</code> headers. It also calculates and sets an ETag if\nneeded.</p>\n</section>\n<section id=\"gzipmiddleware\">\n<h4><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/middleware/#django.middleware.gzip.GZipMiddleware\" title=\"django.middleware.gzip.GZipMiddleware\"><code class=\"xref py py-class docutils literal notranslate\">GZipMiddleware</code></a><a class=\"heading-anchor\" href=\"#gzipmiddleware\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>Compresses responses for all modern browsers, saving bandwidth and transfer\ntime. Note that GZipMiddleware is currently considered a security risk, and is\nvulnerable to attacks that nullify the protection provided by TLS/SSL. See the\nwarning in <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/middleware/#django.middleware.gzip.GZipMiddleware\" title=\"django.middleware.gzip.GZipMiddleware\"><code class=\"xref py py-class docutils literal notranslate\">GZipMiddleware</code></a> for more information.</p>\n</section>\n</section>\n<section id=\"sessions\">\n<h3>会话<a class=\"heading-anchor\" href=\"#sessions\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<section id=\"using-cached-sessions\">\n<h4>Using cached sessions<a class=\"heading-anchor\" href=\"#using-cached-sessions\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p><a class=\"reference internal\" href=\"/zh-hans/2.0/topics/http/sessions/#cached-sessions-backend\"><span class=\"std std-ref\">Using cached sessions</span></a> may be a way to increase\nperformance by eliminating the need to load session data from a slower storage\nsource like the database and instead storing frequently used session data in\nmemory.</p>\n</section>\n</section>\n<section id=\"static-files\">\n<h3>Static files<a class=\"heading-anchor\" href=\"#static-files\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Static files, which by definition are not dynamic, make an excellent target for\noptimization gains.</p>\n<section id=\"cachedstaticfilesstorage\">\n<h4><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/contrib/staticfiles/#django.contrib.staticfiles.storage.CachedStaticFilesStorage\" title=\"django.contrib.staticfiles.storage.CachedStaticFilesStorage\"><code class=\"xref py py-class docutils literal notranslate\">CachedStaticFilesStorage</code></a><a class=\"heading-anchor\" href=\"#cachedstaticfilesstorage\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>By taking advantage of web browsers' caching abilities, you can\neliminate network hits entirely for a given file after the initial download.</p>\n<p><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/contrib/staticfiles/#django.contrib.staticfiles.storage.CachedStaticFilesStorage\" title=\"django.contrib.staticfiles.storage.CachedStaticFilesStorage\"><code class=\"xref py py-class docutils literal notranslate\">CachedStaticFilesStorage</code></a> appends a\ncontent-dependent tag to the filenames of <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/contrib/staticfiles/\"><span class=\"doc\">static files</span></a> to make it safe for browsers to cache them\nlong-term without missing future changes - when a file changes, so will the\ntag, so browsers will reload the asset automatically.</p>\n</section>\n<section id=\"minification\">\n<h4>&quot;Minification&quot;<a class=\"heading-anchor\" href=\"#minification\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>Several third-party Django tools and packages provide the ability to &quot;minify&quot;\nHTML, CSS, and JavaScript. They remove unnecessary whitespace, newlines, and\ncomments, and shorten variable names, and thus reduce the size of the documents\nthat your site publishes.</p>\n</section>\n</section>\n</section>\n<section id=\"template-performance\">\n<h2>Template performance<a class=\"heading-anchor\" href=\"#template-performance\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>Note that:</p>\n<ul class=\"simple\">\n<li><p>using <code class=\"docutils literal notranslate\">{% block %}</code> is faster than using <code class=\"docutils literal notranslate\">{% include %}</code></p></li>\n<li><p>heavily-fragmented templates, assembled from many small pieces, can affect\nperformance</p></li>\n</ul>\n<section id=\"the-cached-template-loader\">\n<h3>The cached template loader<a class=\"heading-anchor\" href=\"#the-cached-template-loader\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Enabling the <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/templates/api/#django.template.loaders.cached.Loader\" title=\"django.template.loaders.cached.Loader\"><code class=\"xref py py-class docutils literal notranslate\">cached template loader</code></a> often improves performance\ndrastically, as it avoids compiling each template every time it needs to be\nrendered.</p>\n</section>\n</section>\n<section id=\"using-different-versions-of-available-software\">\n<h2>Using different versions of available software<a class=\"heading-anchor\" href=\"#using-different-versions-of-available-software\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<p>It can sometimes be worth checking whether different and better-performing\nversions of the software that you're using are available.</p>\n<p>These techniques are targeted at more advanced users who want to push the\nboundaries of performance of an already well-optimized Django site.</p>\n<p>However, they are not magic solutions to performance problems, and they're\nunlikely to bring better than marginal gains to sites that don't already do the\nmore basic things the right way.</p>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">Note</p>\n<p>It's worth repeating: <strong>reaching for alternatives to software you're\nalready using is never the first answer to performance problems</strong>. When\nyou reach this level of optimization, you need a formal benchmarking\nsolution.</p>\n</aside>\n<section id=\"newer-is-often-but-not-always-better\">\n<h3>Newer is often - but not always - better<a class=\"heading-anchor\" href=\"#newer-is-often-but-not-always-better\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>It's fairly rare for a new release of well-maintained software to be less\nefficient, but the maintainers can't anticipate every possible use-case - so\nwhile being aware that newer versions are likely to perform better, don't\nsimply assume that they always will.</p>\n<p>This is true of Django itself. Successive releases have offered a number of\nimprovements across the system, but you should still check the real-world\nperformance of your application, because in some cases you may find that\nchanges mean it performs worse rather than better.</p>\n<p>Newer versions of Python, and also of Python packages, will often perform\nbetter too - but measure, rather than assume.</p>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">Note</p>\n<p>Unless you've encountered an unusual performance problem in a particular\nversion, you'll generally find better features, reliability, and security\nin a new release and that these benefits are far more significant than any\nperformance you might win or lose.</p>\n</aside>\n</section>\n<section id=\"alternatives-to-django-s-template-language\">\n<h3>Alternatives to Django's template language<a class=\"heading-anchor\" href=\"#alternatives-to-django-s-template-language\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>For nearly all cases, Django's built-in template language is perfectly\nadequate. However, if the bottlenecks in your Django project seem to lie in the\ntemplate system and you have exhausted other opportunities to remedy this, a\nthird-party alternative may be the answer.</p>\n<p><a class=\"reference external\" href=\"http://jinja.pocoo.org/docs/\">Jinja2</a> can offer performance improvements,\nparticularly when it comes to speed.</p>\n<p>Alternative template systems vary in the extent to which they share Django's\ntemplating language.</p>\n<aside class=\"admonition admonition-note\" role=\"note\">\n<p class=\"admonition-title\">Note</p>\n<p><em>If</em> you experience performance issues in templates, the first thing to do\nis to understand exactly why. Using an alternative template system may\nprove faster, but the same gains may also be available without going to\nthat trouble - for example, expensive processing and logic in your\ntemplates could be done more efficiently in your views.</p>\n</aside>\n</section>\n<section id=\"alternative-software-implementations\">\n<h3>Alternative software implementations<a class=\"heading-anchor\" href=\"#alternative-software-implementations\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>It may be worth checking whether Python software you're using has been\nprovided in a different implementation that can execute the same code faster.</p>\n<p>However: most performance problems in well-written Django sites aren't at the\nPython execution level, but rather in inefficient database querying, caching,\nand templates. If you're relying on poorly-written Python code, your\nperformance problems are unlikely to be solved by having it execute faster.</p>\n<p>Using an alternative implementation may introduce compatibility, deployment,\nportability, or maintenance issues. It goes without saying that before adopting\na non-standard implementation you should ensure it provides sufficient\nperformance gains for your application to outweigh the potential risks.</p>\n<p>With these caveats in mind, you should be aware of:</p>\n<section id=\"id1\">\n<h4><a class=\"reference external\" href=\"https://pypy.org/\">PyPy</a><a class=\"heading-anchor\" href=\"#id1\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p><a class=\"reference external\" href=\"https://pypy.org/\">PyPy</a> is an implementation of Python in Python itself\n(the 'standard' Python implementation is in C). PyPy can offer substantial\nperformance gains, typically for heavyweight applications.</p>\n<p>A key aim of the PyPy project is <a class=\"reference external\" href=\"https://pypy.org/compat.html\">compatibility</a> with existing Python APIs and libraries.\nDjango is compatible, but you will need to check the compatibility of other\nlibraries you rely on.</p>\n</section>\n<section id=\"c-implementations-of-python-libraries\">\n<h4>C implementations of Python libraries<a class=\"heading-anchor\" href=\"#c-implementations-of-python-libraries\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>Some Python libraries are also implemented in C, and can be much faster. They\naim to offer the same APIs. Note that compatibility issues and behavior\ndifferences are not unknown (and not always immediately evident).</p>\n</section>\n</section>\n</section>","rootId":"performance-and-optimization","toc":[{"title":"介绍","anchor":"introduction","children":[]},{"title":"一般方法","anchor":"general-approaches","children":[{"title":"你在*为*什么而优化？","anchor":"what-are-you-optimizing-for","children":[]},{"title":"性能标竿","anchor":"performance-benchmarking","children":[{"title":"Django工具","anchor":"django-tools","children":[]},{"title":"第三方服务","anchor":"third-party-services","children":[]}]},{"title":"Get things right from the start","anchor":"get-things-right-from-the-start","children":[{"title":"Work at the appropriate level","anchor":"work-at-the-appropriate-level","children":[]}]}]},{"title":"Caching","anchor":"caching","children":[{"title":"The caching framework","anchor":"the-caching-framework","children":[]},{"title":"cached_property","anchor":"cached-property","children":[]}]},{"title":"Understanding laziness","anchor":"understanding-laziness","children":[{"title":"Laziness in Django","anchor":"laziness-in-django","children":[]}]},{"title":"Databases","anchor":"databases","children":[{"title":"Database optimization","anchor":"database-optimization","children":[]},{"title":"Other database-related tips","anchor":"other-database-related-tips","children":[]}]},{"title":"HTTP performance","anchor":"http-performance","children":[{"title":"中间件","anchor":"middleware","children":[{"title":"ConditionalGetMiddleware","anchor":"conditionalgetmiddleware","children":[]},{"title":"GZipMiddleware","anchor":"gzipmiddleware","children":[]}]},{"title":"会话","anchor":"sessions","children":[{"title":"Using cached sessions","anchor":"using-cached-sessions","children":[]}]},{"title":"Static files","anchor":"static-files","children":[{"title":"CachedStaticFilesStorage","anchor":"cachedstaticfilesstorage","children":[]},{"title":"\"Minification\"","anchor":"minification","children":[]}]}]},{"title":"Template performance","anchor":"template-performance","children":[{"title":"The cached template loader","anchor":"the-cached-template-loader","children":[]}]},{"title":"Using different versions of available software","anchor":"using-different-versions-of-available-software","children":[{"title":"Newer is often - but not always - better","anchor":"newer-is-often-but-not-always-better","children":[]},{"title":"Alternatives to Django's template language","anchor":"alternatives-to-django-s-template-language","children":[]},{"title":"Alternative software implementations","anchor":"alternative-software-implementations","children":[{"title":"PyPy","anchor":"id1","children":[]},{"title":"C implementations of Python libraries","anchor":"c-implementations-of-python-libraries","children":[]}]}]}],"breadcrumbs":[{"docname":"topics/index","title":"Using Django","url":"/zh-hans/2.0/topics/"}],"prev":{"docname":"topics/security","title":"Security in Django","url":"/zh-hans/2.0/topics/security/"},"next":{"docname":"topics/serialization","title":"Serializing Django objects","url":"/zh-hans/2.0/topics/serialization/"},"formats":{"html":"/zh-hans/2.0/topics/performance/","markdown":"/zh-hans/2.0/topics/performance.md","json":"/zh-hans/2.0/topics/performance.json"},"source":"https://github.com/django/django/blob/stable/2.0.x/docs/topics/performance.txt","official":"https://docs.djangoproject.com/zh-hans/2.0/topics/performance/","inVersions":["6.1","6.0","5.2","5.1","5.0","4.2","4.1","4.0","3.2","3.1","3.0","2.2","2.1","2.0"],"inLocales":["en","zh-hans","fr","ja","id","pt-br","ko","es","el","pl"]}