{"title":"パフォーマンスと最適化","version":"4.2","locale":"ja","docname":"topics/performance","url":"/ja/4.2/topics/performance/","canonical":"https://djangodocs.dev/ja/4.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>1つの領域を改善すると、別の領域の性能も向上することがよくありますが、常にそうとは限らず、一方が他方を犠牲にすることさえあります。たとえば、プログラムの速度の改善がメモリ使用量の増加を引き起こすかもしれません。さらに悪いことに、それが自滅的になるかもしれません。もし速度の改善がメモリを大幅に消費してしまったら、システム上のメモリが足りなくなり、結果的に利益よりも害を与えることになってしまうでしょう。</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 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/\">Google PageSpeed</a></p></li>\n</ul>\n<p>同様の分析を実施する有料サービスもいくつかあり、一部は Django を認識するため、コードベースと統合して性能のプロファイルをより包括的に得られます。</p>\n</section>\n</section>\n<section id=\"get-things-right-from-the-start\">\n<h3>最初から物事を正しく行う<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 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>適切なレベルで作業する<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</code></pre></div>\n<div class=\"code-block\" data-language=\"html+django\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Django template</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=\"Django template code\"><code><span class=\"cm\">&lt;!--</span>\n<span class=\"cm\">Django template filter</span>\n<span class=\"cm\">slower still, because it will have to count them in Python anyway,</span>\n<span class=\"cm\">and because of template language overheads</span>\n<span class=\"cm\">--&gt;</span>\n<span class=\"cp\">{{</span> <span class=\"nv\">my_bicycles</span><span class=\"o\">|</span><span class=\"nf\">length</span> <span class=\"cp\">}}</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/4.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/4.2/topics/cache/\"><span class=\"doc\">キャッシュフレームワーク</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/4.2/topics/cache/\"><span class=\"doc\">キャッシュフレームワーク</span></a> は、動的なコンテンツを保存して、リクエストごとに再計算しないで済むようにすることで、パフォーマンスを向上するための非常に大きな可能性を提供します。</p>\n<p>利便性のため、Django は様々なレベルのキャッシュの粒度を提供しています。特定のビューの出力をキャッシュしたり、生成するのに時間のかかるパーツだけをキャッシュしたり、あるいは、サイト全体をキャッシュすることでさえ可能です。</p>\n<p>キャッシュの実装は性能の悪いコードの改善の代わりとするべきではありません。なぜならそのコードはよく書かれていないからです。キャッシュは優れた性能のコードを書くための最終ステップの1つであり、ショートカットではありません。</p>\n</section>\n<section id=\"cached-property\">\n<h3><a class=\"reference internal\" href=\"/ja/4.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/4.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>遅延によりインスタンス化される前に、またはインスタンス化が可能になる以前であっても参照できるようになります。これにはさまざまな用途があります。</p>\n<p>たとえば、<a class=\"reference internal\" href=\"/ja/4.2/topics/i18n/translation/#lazy-translations\"><span class=\"std std-ref\">遅延翻訳</span></a> は対象となる言語自体が判別される前に使用できます。翻訳後の文字列がレンダリングされたテンプレートなどで実際に必要になるまで使用されなくなるためです。</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 自体が非常に遅延性が高いです。このよい例として、<code class=\"docutils literal notranslate\"><span class=\"pre\">QuerySets</span></code> の評価が挙げられます。<a class=\"reference internal\" href=\"/ja/4.2/topics/db/queries/#querysets-are-lazy\"><span class=\"std std-ref\">QuerySets は遅延します</span></a>。そのため、<code class=\"docutils literal notranslate\"><span class=\"pre\">QuerySet</span></code> は作成後、記述したアイテムを取得するためにデータベースへのアクセスを一切行うことなく、さまざまな場所に渡したり、他の <code class=\"docutils literal notranslate\"><span class=\"pre\">QuerySets</span></code> と組み合わせることができます。渡されるのは <code class=\"docutils literal notranslate\"><span class=\"pre\">QuerySet</span></code> オブジェクトであって、最終的にはデータベースから取得されるアイテムのコレクションではないのです。</p>\n<p>他方で、<a class=\"reference internal\" href=\"/ja/4.2/ref/models/querysets/#when-querysets-are-evaluated\"><span class=\"std std-ref\">特定の操作は QuerySet の評価を強制します</span></a>。<code class=\"docutils literal notranslate\"><span class=\"pre\">QuerySet</span></code> の時期尚早な評価を回避することで、高価で不必要なデータベースへのアクセスを節約できます。</p>\n<p>Django also offers a <a class=\"reference internal\" href=\"/ja/4.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のデータベース層は、開発者がデータベースを最大限活用できるように、さまざまな方法を提供しています。 <a class=\"reference internal\" href=\"/ja/4.2/topics/db/optimization/\"><span class=\"doc\">データベースアクセスの最適化ドキュメント</span></a> では、データベースの利用を最適化する際にとるべき手順を、大まかにいくつかの見出しとしてまとめています。それぞれの見出しの下に、関連するドキュメントへのリンクを集約した上で、さまざまなヒントを追加しています。</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><a class=\"reference internal\" href=\"/ja/4.2/ref/databases/#persistent-database-connections\"><span class=\"std std-ref\">永続的な接続</span></a> を有効化すると、リクエストの処理時間のかなりの部分を占めるデータベースへの接続が高速化できます。</p>\n<p>これは、たとえばネットワーク性能が限定された仮想化ホストにおいて、とても効果的です。</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/4.2/ref/middleware/\"><span class=\"doc\">middleware</span></a> を用意しています。以下のようなものがあります。</p>\n<section id=\"conditionalgetmiddleware\">\n<h4><a class=\"reference internal\" href=\"/ja/4.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>モダンなブラウザが <code class=\"docutils literal notranslate\"><span class=\"pre\">ETag</span></code> と <code class=\"docutils literal notranslate\"><span class=\"pre\">Last-Modified</span></code> ヘッダを元に条件的にレスポンスを GET するためのサポートを追加します。</p>\n</section>\n<section id=\"gzipmiddleware\">\n<h4><a class=\"reference internal\" href=\"/ja/4.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/4.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/4.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/4.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/4.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/4.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>注意:</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/4.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\nassume 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=\"https://jinja.palletsprojects.com/\">Jinja2</a> can offer performance improvements, particularly when it comes to\nspeed.</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://www.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://www.pypy.org/\">PyPy</a> は Python 自身で書かれた Python 実装です ('標準の' Python 実装は C で書かれています)。heavyweight なアプリケーションの場合、PyPy を使用するとパフォーマンスが大幅に向上する可能性があります。</p>\n<p>PyPy プロジェクトの主目的の1つは、既存の Python API とライブラリとの <a class=\"reference external\" href=\"https://www.pypy.org/compat.html\">互換性</a> です。Django は互換性がありますが、他の依存ライブラリの互換性については確認が必要です。</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":"最初から物事を正しく行う","anchor":"get-things-right-from-the-start","children":[{"title":"適切なレベルで作業する","anchor":"work-at-the-appropriate-level","children":[]}]}]},{"title":"Caching","anchor":"caching","children":[{"title":"キャッシュフレームワーク","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/4.2/topics/"}],"prev":{"docname":"topics/security","title":"Django におけるセキュリティ","url":"/ja/4.2/topics/security/"},"next":{"docname":"topics/serialization","title":"Django オブジェクトのシリアル化","url":"/ja/4.2/topics/serialization/"},"formats":{"html":"/ja/4.2/topics/performance/","markdown":"/ja/4.2/topics/performance.md","json":"/ja/4.2/topics/performance.json"},"source":"https://github.com/django/django/blob/stable/4.2.x/docs/topics/performance.txt","official":"https://docs.djangoproject.com/ja/4.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","it","pt-br","ko","es","el","pl"]}