{"title":"パフォーマンスと最適化","version":"2.2","locale":"ja","docname":"topics/performance","url":"/ja/2.2/topics/performance/","canonical":"https://djangodocs.dev/ja/2.2/topics/performance/","summary":"このドキュメントでは、Django コードをより効率よく、早く、より少ないリソースで実行するためのテクニックとツールについて、その概要を説明します。 はじめに Link to this heading # 一般に、最も関心があるのは、コードが正しく 動作する…","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>一般に、最も関心があるのは、コードが正しく <em>動作する</em>、つまり、書かれたコードのロジックがが期待通りの出力を生成することです。しかし、それだけでは、期待通りに <em>効率よく</em> 動作しているとは言えません。</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><em>何のために</em> 最適化をしようとしているのか？<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>最適化する「パフォーマンス」という言葉で何を意味しているのか、はっきりと考えておくことが大切です。パフォーマンスを測る指標は1つではないからです。</p>\n<p>高速化というものがプログラムのために最も明らかな目的かもしれません。しかし、他の観点からパフォーマンスを向上することもできます。たとえば、メモリー消費量を少なくするとか、データベースやネットワークのアクセス量を削減するといったことが考えられます。</p>\n<p>Improvements in one area will often bring about improved performance in\nanother, but not always; sometimes one can even be at the expense of another.\nFor example, an improvement in a program's speed might cause it to use more\nmemory. Even worse, it can be self-defeating - if the speed improvement is so\nmemory-hungry that the system starts to run out of memory, you'll have done\nmore harm than good.</p>\n<p>There are other trade-offs to bear in mind. Your own time is a valuable\nresource, more precious than CPU time. Some improvements might be too difficult\nto be worth implementing, or might affect the portability or maintainability of\nthe code. Not all performance improvements are worth the effort.</p>\n<p>So, you need to know what performance improvements you are aiming for, and you\nalso need to know that you have a good reason for aiming in that direction -\nand for that you need:</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 class=\"reference external\" href=\"https://github.com/jazzband/django-debug-toolbar/\">django-debug-toolbar</a> は、コードの動作や実行時間を確認する手段を提供してくれる、非常に便利なツールです。特に、ページが生成するすべての 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>サイト上のページのパフォーマンスを分析・レポートしてくれる無料のサービスが数多く存在します。これらのサービスでは、実際のユーザーエクスペリエンスをリモートの HTTP クライアントの観点からシミュレートしてくれます。</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\"><span class=\"pre\">QuerySet</span></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>\n<span class=\"n\">my_bicycles</span><span class=\"o\">.</span><span class=\"n\">count</span><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><span class=\"n\">my_bicycles</span><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> <span class=\"n\">my_bicycles</span><span class=\"o\">|</span><span class=\"n\">length</span> <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\">注釈</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=\"/ja/2.2/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\"><span class=\"pre\">{{</span>\n<span class=\"pre\">my_bicycles.count</span> <span class=\"pre\">}}</span></code>, which invokes the <code class=\"docutils literal notranslate\"><span class=\"pre\">QuerySet</span></code> <code class=\"docutils literal notranslate\"><span class=\"pre\">count()</span></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=\"/ja/2.2/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 の <a class=\"reference internal\" href=\"/ja/2.2/topics/cache/\"><span class=\"doc\">caching framework</span></a> は、動的なコンテンツを保存して、リクエストごとに再計算しないで済むようにすることで、パフォーマンスを向上するための非常に大きな可能性を提供します。</p>\n<p>利便性のため、Django は様々なレベルのキャッシュの粒度を提供しています。特定のビューの出力をキャッシュしたり、生成するのに時間のかかるパーツだけをキャッシュしたり、あるいは、サイト全体をキャッシュすることでさえ可能です。</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=\"/ja/2.2/ref/utils/#django.utils.functional.cached_property\" title=\"django.utils.functional.cached_property\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">cached_property</span></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>クラスのインスタンスのメソッドを複数回呼ぶ必要があるというのはよくあることです。その関数の実行が高価な場合、複数回の呼び出しは資源の浪費になります。</p>\n<p><a class=\"reference internal\" href=\"/ja/2.2/ref/utils/#django.utils.functional.cached_property\" title=\"django.utils.functional.cached_property\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">cached_property</span></code></a> デコレータを使うことで、プロパティが返す値を保存して、次回同じインスタンスで関数が呼ばれた時、その値を再計算する代わりに、保存しておいた値を返すようにすることができます。ただし、このデコレータが機能するのは、メソッドが引数として <code class=\"docutils literal notranslate\"><span class=\"pre\">self</span></code> のみを取り、メソッドをプロパティーに変えられる場合のみなので、注意してください。</p>\n<p>特定の Django コンポーネントは、独自のキャッシュ機能を実装しています。以下のそれらのコンポーネントに関係するセクションで解説します。</p>\n</section>\n</section>\n<section id=\"understanding-laziness\">\n<h2>遅延について理解する<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> とは、キャッシュ機能を補完するもう1つの戦略です。キャッシュは結果を保存することで再計算を防ぎますが、遅延は実際に値が必要になるまで、計算の実行を遅らせます。</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=\"/ja/2.2/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>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\"><span class=\"pre\">QuerySets</span></code>. <a class=\"reference internal\" href=\"/ja/2.2/topics/db/queries/#querysets-are-lazy\"><span class=\"std std-ref\">QuerySets are lazy</span></a>.\nThus a <code class=\"docutils literal notranslate\"><span class=\"pre\">QuerySet</span></code> can be created, passed around and combined with other\n<code class=\"docutils literal notranslate\"><span class=\"pre\">QuerySets</span></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\"><span class=\"pre\">QuerySet</span></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=\"/ja/2.2/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\"><span class=\"pre\">QuerySet</span></code> can save making an expensive and unnecessary trip to the\ndatabase.</p>\n<p>Django also offers a <a class=\"reference internal\" href=\"/ja/2.2/ref/utils/#django.utils.functional.keep_lazy\" title=\"django.utils.functional.keep_lazy\"><code class=\"xref py py-meth docutils literal notranslate\"><span class=\"pre\">keep_lazy()</span></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>データベース<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>データベースの最適化<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=\"/ja/2.2/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>その他のデータベース関連の 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=\"/ja/2.2/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 のパフォーマンス<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>ミドルウェア (Middleware)<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 は、サイトのパフォーマンス改善に役立ついくつかの <a class=\"reference internal\" href=\"/ja/2.2/ref/middleware/\"><span class=\"doc\">middleware</span></a> を用意しています。以下のようなものがあります。</p>\n<section id=\"conditionalgetmiddleware\">\n<h4><a class=\"reference internal\" href=\"/ja/2.2/ref/middleware/#django.middleware.http.ConditionalGetMiddleware\" title=\"django.middleware.http.ConditionalGetMiddleware\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">ConditionalGetMiddleware</span></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\"><span class=\"pre\">ETag</span></code> and <code class=\"docutils literal notranslate\"><span class=\"pre\">Last-Modified</span></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=\"/ja/2.2/ref/middleware/#django.middleware.gzip.GZipMiddleware\" title=\"django.middleware.gzip.GZipMiddleware\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">GZipMiddleware</span></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=\"/ja/2.2/ref/middleware/#django.middleware.gzip.GZipMiddleware\" title=\"django.middleware.gzip.GZipMiddleware\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">GZipMiddleware</span></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>キャッシュを使ったセッション<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=\"/ja/2.2/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>静的ファイル<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>静的ファイル (定義により、動的に生成されないファイル) は、最適化を施すのに格好のターゲットです。</p>\n<section id=\"manifeststaticfilesstorage\">\n<h4><a class=\"reference internal\" href=\"/ja/2.2/ref/contrib/staticfiles/#django.contrib.staticfiles.storage.ManifestStaticFilesStorage\" title=\"django.contrib.staticfiles.storage.ManifestStaticFilesStorage\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">ManifestStaticFilesStorage</span></code></a><a class=\"heading-anchor\" href=\"#manifeststaticfilesstorage\"><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=\"/ja/2.2/ref/contrib/staticfiles/#django.contrib.staticfiles.storage.ManifestStaticFilesStorage\" title=\"django.contrib.staticfiles.storage.ManifestStaticFilesStorage\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">ManifestStaticFilesStorage</span></code></a> appends a\ncontent-dependent tag to the filenames of <a class=\"reference internal\" href=\"/ja/2.2/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>いくつかのサードパーティ製の Django ツールやパッケージは、HTML、CSS、そして JavaScript を最小化する (&quot;minify&quot;) 機能を提供します。これらは不要なホワイトスペースや改行、コメントを取り除き、変数名を短縮することで、サイトが公開するドキュメントのサイズを削減してくれます。</p>\n</section>\n</section>\n</section>\n<section id=\"template-performance\">\n<h2>テンプレートのパフォーマンス<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><code class=\"docutils literal notranslate\"><span class=\"pre\">{%</span> <span class=\"pre\">block</span> <span class=\"pre\">%}</span></code> の使用は <code class=\"docutils literal notranslate\"><span class=\"pre\">{%</span> <span class=\"pre\">include</span> <span class=\"pre\">%}</span></code> より高速です。</p></li>\n<li><p>多数の分割されたテンプレートパーツからページを生成すると、パフォーマンスに影響することがあります。</p></li>\n</ul>\n<section id=\"the-cached-template-loader\">\n<h3>キャッシュテンプレートローダー<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><a class=\"reference internal\" href=\"/ja/2.2/ref/templates/api/#django.template.loaders.cached.Loader\" title=\"django.template.loaders.cached.Loader\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">cached</span> <span class=\"pre\">template</span> <span class=\"pre\">loader</span></code></a> を有効にすると、パフォーマンスが劇的に改善する場合が多いです。このローダーを使用することで、テンプレートのレンダリングが必要になった場合に、各テンプレートを毎回コンパイルせずに済むようになるためです。</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\">注釈</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>新しいものは (常にとはいえないけれども) より良いものである<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\">注釈</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>Django テンプレート言語の代替<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> を使うと、パフォーマンス、特に速度の向上が得られる可能性があります。</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\">注釈</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>代替のソフトウェア実装<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>Python ライブラリの C 実装<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":"遅延について理解する","anchor":"understanding-laziness","children":[{"title":"Django における遅延","anchor":"laziness-in-django","children":[]}]},{"title":"データベース","anchor":"databases","children":[{"title":"データベースの最適化","anchor":"database-optimization","children":[]},{"title":"その他のデータベース関連の tips","anchor":"other-database-related-tips","children":[]}]},{"title":"HTTP のパフォーマンス","anchor":"http-performance","children":[{"title":"ミドルウェア (Middleware)","anchor":"middleware","children":[{"title":"ConditionalGetMiddleware","anchor":"conditionalgetmiddleware","children":[]},{"title":"GZipMiddleware","anchor":"gzipmiddleware","children":[]}]},{"title":"セッション","anchor":"sessions","children":[{"title":"キャッシュを使ったセッション","anchor":"using-cached-sessions","children":[]}]},{"title":"静的ファイル","anchor":"static-files","children":[{"title":"ManifestStaticFilesStorage","anchor":"manifeststaticfilesstorage","children":[]},{"title":"\"Minification\"","anchor":"minification","children":[]}]}]},{"title":"テンプレートのパフォーマンス","anchor":"template-performance","children":[{"title":"キャッシュテンプレートローダー","anchor":"the-cached-template-loader","children":[]}]},{"title":"Using different versions of available software","anchor":"using-different-versions-of-available-software","children":[{"title":"新しいものは (常にとはいえないけれども) より良いものである","anchor":"newer-is-often-but-not-always-better","children":[]},{"title":"Django テンプレート言語の代替","anchor":"alternatives-to-django-s-template-language","children":[]},{"title":"代替のソフトウェア実装","anchor":"alternative-software-implementations","children":[{"title":"PyPy","anchor":"id1","children":[]},{"title":"Python ライブラリの C 実装","anchor":"c-implementations-of-python-libraries","children":[]}]}]}],"breadcrumbs":[{"docname":"topics/index","title":"Django を使う","url":"/ja/2.2/topics/"}],"prev":{"docname":"topics/security","title":"Django におけるセキュリティ","url":"/ja/2.2/topics/security/"},"next":{"docname":"topics/serialization","title":"Django オブジェクトのシリアル化","url":"/ja/2.2/topics/serialization/"},"formats":{"html":"/ja/2.2/topics/performance/","markdown":"/ja/2.2/topics/performance.md","json":"/ja/2.2/topics/performance.json"},"source":"https://github.com/django/django/blob/stable/2.2.x/docs/topics/performance.txt","official":"https://docs.djangoproject.com/ja/2.2/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","1.11","1.10","1.9"],"inLocales":["en","zh-hans","fr","ja","id","pt-br","ko","es","el","pl"]}