パフォーマンスと最適化Link to this heading
このドキュメントでは、Django コードをより効率よく、早く、より少ないリソースで実行するためのテクニックとツールについて、その概要を説明します。
はじめにLink to this heading
一般に、最も関心があるのは、コードが正しく 動作する、つまり、書かれたコードのロジックがが期待通りの出力を生成することです。しかし、それだけでは、期待通りに 効率よく 動作しているとは言えません。
この場合、必要なのは、コードの振る舞いに影響を与えることなく、あるいは影響を最小限に保ちつつ、そのパフォーマンスを向上させる実用的な方法です。
一般的なアプローチLink to this heading
何のために 最適化をしようとしているのか?Link to this heading
最適化する「パフォーマンス」という言葉で何を意味しているのか、はっきりと考えておくことが大切です。パフォーマンスを測る指標は1つではないからです。
高速化というものがプログラムのために最も明らかな目的かもしれません。しかし、他の観点からパフォーマンスを向上することもできます。たとえば、メモリー消費量を少なくするとか、データベースやネットワークのアクセス量を削減するといったことが考えられます。
1つの領域を改善すると、別の領域の性能も向上することがよくありますが、常にそうとは限らず、一方が他方を犠牲にすることさえあります。たとえば、プログラムの速度の改善がメモリ使用量の増加を引き起こすかもしれません。さらに悪いことに、それが自滅的になるかもしれません。もし速度の改善がメモリを大幅に消費してしまったら、システム上のメモリが足りなくなり、結果的に利益よりも害を与えることになってしまうでしょう。
他にも気に留めておく必要があるトレードオフがあります。あなた自身の時間が CPU 時間以上に貴重なリソースだということです。一部の改善は実装する価値がないほど難しすぎるかもしれず、ポータビリティやコードメンテナンスに影響を与えてしまうかもしれません。すべての性能改善に努力する価値があるわけではないのです。
そのため、何を目的としたパフォーマンスの改善なのかを知っておくべき必要があります。また、その目的とした方針に相応の理由があるかを知っておく必要もあります。
パフォーマンスのベンチマークLink to this heading
コード中で効率の悪い部分を、単に想像したり当て推量したりするというのは、あまり良い考えではありません。
Django のツールLink to this heading
django-debug-toolbar は、コードの動作や実行時間を確認する手段を提供してくれる、非常に便利なツールです。特に、ページが生成するすべての SQL クエリと、そのそれぞれの実行時間を表示してくれる機能が有用です。
サードパーティ製のパネルをツールバーに追加することも可能です。それにより、たとえば、キャッシュのパフォーマンスや、テンプレートのレンダリング時間を測定することができます。
サードパーティのサービスLink to this heading
サイト上のページのパフォーマンスを分析・レポートしてくれる無料のサービスが数多く存在します。これらのサービスでは、実際のユーザーエクスペリエンスをリモートの HTTP クライアントの観点からシミュレートしてくれます。
These can't report on the internals of your code, but can provide a useful insight into your site's overall performance, including aspects that can't be adequately measured from within Django environment. Examples include:
同様の分析を実施する有料サービスもいくつかあり、一部は Django を認識するため、コードベースと統合して性能のプロファイルをより包括的に得られます。
最初から物事を正しく行うLink to this heading
Some work in optimization involves tackling performance shortcomings, but some of the work can be built-in to what you'd do anyway, as part of the good practices you should adopt even before you start thinking about improving performance.
In this respect Python is an excellent language to work with, because solutions that look elegant and feel right usually are the best performing ones. As with most skills, learning what "looks right" takes practice, but one of the most useful guidelines is:
適切なレベルで作業するLink to this heading
Django offers many different ways of approaching things, but just because it's
possible to do something in a certain way doesn't mean that it's the most
appropriate way to do it. For example, you might find that you could calculate
the same thing - the number of items in a collection, perhaps - in a
QuerySet, in Python, or in a template.
However, it will almost always be faster to do this work at lower rather than higher levels. At higher levels the system has to deal with objects through multiple levels of abstraction and layers of machinery.
That is, the database can typically do things faster than Python can, which can do them faster than the template language can:
# QuerySet operation on the database
# fast, because that's what databases are good at
my_bicycles.count()
# counting Python objects
# slower, because it requires a database query anyway, and processing
# of the Python objects
len(my_bicycles)
<!--
Django template filter
slower still, because it will have to count them in Python anyway,
and because of template language overheads
-->
{{ my_bicycles|length }}
Generally speaking, the most appropriate level for the job is the lowest-level one that it is comfortable to code for.
CachingLink to this heading
Often it is expensive (that is, resource-hungry and slow) to compute a value, so there can be huge benefit in saving the value to a quickly accessible cache, ready for the next time it's required.
It's a sufficiently significant and powerful technique that Django includes a comprehensive caching framework, as well as other smaller pieces of caching functionality.
キャッシュフレームワークLink to this heading
Django の キャッシュフレームワーク は、動的なコンテンツを保存して、リクエストごとに再計算しないで済むようにすることで、パフォーマンスを向上するための非常に大きな可能性を提供します。
利便性のため、Django は様々なレベルのキャッシュの粒度を提供しています。特定のビューの出力をキャッシュしたり、生成するのに時間のかかるパーツだけをキャッシュしたり、あるいは、サイト全体をキャッシュすることでさえ可能です。
キャッシュの実装は性能の悪いコードの改善の代わりとするべきではありません。なぜならそのコードはよく書かれていないからです。キャッシュは優れた性能のコードを書くための最終ステップの1つであり、ショートカットではありません。
cached_propertyLink to this heading
クラスのインスタンスのメソッドを複数回呼ぶ必要があるというのはよくあることです。その関数の実行が高価な場合、複数回の呼び出しは資源の浪費になります。
cached_property デコレータを使うことで、プロパティが返す値を保存して、次回同じインスタンスで関数が呼ばれた時、その値を再計算する代わりに、保存しておいた値を返すようにすることができます。ただし、このデコレータが機能するのは、メソッドが引数として self のみを取り、メソッドをプロパティーに変えられる場合のみなので、注意してください。
特定の Django コンポーネントは、独自のキャッシュ機能を実装しています。以下のそれらのコンポーネントに関係するセクションで解説します。
遅延について理解するLink to this heading
遅延 (laziness) とは、キャッシュ機能を補完するもう1つの戦略です。キャッシュは結果を保存することで再計算を防ぎますが、遅延は実際に値が必要になるまで、計算の実行を遅らせます。
遅延によりインスタンス化される前に、またはインスタンス化が可能になる以前であっても参照できるようになります。これにはさまざまな用途があります。
たとえば、遅延翻訳 は対象となる言語自体が判別される前に使用できます。翻訳後の文字列がレンダリングされたテンプレートなどで実際に必要になるまで使用されなくなるためです。
Laziness is also a way to save effort by trying to avoid work in the first place. That is, one aspect of laziness is not doing anything until it has to be done, because it may not turn out to be necessary after all. Laziness can therefore have performance implications, and the more expensive the work concerned, the more there is to gain through laziness.
Python provides a number of tools for lazy evaluation, particularly through the generator and generator expression constructs. It's worth reading up on laziness in Python to discover opportunities for making use of lazy patterns in your code.
Django における遅延Link to this heading
Django 自体が非常に遅延性が高いです。このよい例として、QuerySets の評価が挙げられます。QuerySets は遅延します。そのため、QuerySet は作成後、記述したアイテムを取得するためにデータベースへのアクセスを一切行うことなく、さまざまな場所に渡したり、他の QuerySets と組み合わせることができます。渡されるのは QuerySet オブジェクトであって、最終的にはデータベースから取得されるアイテムのコレクションではないのです。
他方で、特定の操作は QuerySet の評価を強制します。QuerySet の時期尚早な評価を回避することで、高価で不必要なデータベースへのアクセスを節約できます。
Django also offers a keep_lazy() decorator.
This allows a function that has been called with a lazy argument to behave
lazily itself, only being evaluated when it needs to be. Thus the lazy argument
- which could be an expensive one - will not be called upon for evaluation
until it's strictly required.
データベースLink to this heading
データベースの最適化Link to this heading
Djangoのデータベース層は、開発者がデータベースを最大限活用できるように、さまざまな方法を提供しています。 データベースアクセスの最適化ドキュメント では、データベースの利用を最適化する際にとるべき手順を、大まかにいくつかの見出しとしてまとめています。それぞれの見出しの下に、関連するドキュメントへのリンクを集約した上で、さまざまなヒントを追加しています。
HTTP のパフォーマンスLink to this heading
ミドルウェア (Middleware)Link to this heading
Django は、サイトのパフォーマンス改善に役立ついくつかの middleware を用意しています。以下のようなものがあります。
ConditionalGetMiddlewareLink to this heading
モダンなブラウザが ETag と Last-Modified ヘッダを元に条件的にレスポンスを GET するためのサポートを追加します。
GZipMiddlewareLink to this heading
Compresses responses for all modern browsers, saving bandwidth and transfer
time. Note that GZipMiddleware is currently considered a security risk, and is
vulnerable to attacks that nullify the protection provided by TLS/SSL. See the
warning in GZipMiddleware for more information.
セッションLink to this heading
キャッシュを使ったセッションLink to this heading
Using cached sessions may be a way to increase performance by eliminating the need to load session data from a slower storage source like the database and instead storing frequently used session data in memory.
静的ファイルLink to this heading
静的ファイル (定義により、動的に生成されないファイル) は、最適化を施すのに格好のターゲットです。
ManifestStaticFilesStorageLink to this heading
By taking advantage of web browsers' caching abilities, you can eliminate network hits entirely for a given file after the initial download.
ManifestStaticFilesStorage appends a
content-dependent tag to the filenames of static files to make it safe for browsers to cache them
long-term without missing future changes - when a file changes, so will the
tag, so browsers will reload the asset automatically.
"Minification"Link to this heading
いくつかのサードパーティ製の Django ツールやパッケージは、HTML、CSS、そして JavaScript を最小化する ("minify") 機能を提供します。これらは不要なホワイトスペースや改行、コメントを取り除き、変数名を短縮することで、サイトが公開するドキュメントのサイズを削減してくれます。
テンプレートのパフォーマンスLink to this heading
注意:
{% block %}の使用は{% include %}より高速です。多数の分割されたテンプレートパーツからページを生成すると、パフォーマンスに影響することがあります。
キャッシュテンプレートローダーLink to this heading
cached template loader を有効にすると、パフォーマンスが劇的に改善する場合が多いです。このローダーを使用することで、テンプレートのレンダリングが必要になった場合に、各テンプレートを毎回コンパイルせずに済むようになるためです。
Using different versions of available softwareLink to this heading
It can sometimes be worth checking whether different and better-performing versions of the software that you're using are available.
These techniques are targeted at more advanced users who want to push the boundaries of performance of an already well-optimized Django site.
However, they are not magic solutions to performance problems, and they're unlikely to bring better than marginal gains to sites that don't already do the more basic things the right way.
新しいものは (常にとはいえないけれども) より良いものであるLink to this heading
It's fairly rare for a new release of well-maintained software to be less efficient, but the maintainers can't anticipate every possible use-case - so while being aware that newer versions are likely to perform better, don't assume that they always will.
This is true of Django itself. Successive releases have offered a number of improvements across the system, but you should still check the real-world performance of your application, because in some cases you may find that changes mean it performs worse rather than better.
Newer versions of Python, and also of Python packages, will often perform better too - but measure, rather than assume.
Django テンプレート言語の代替Link to this heading
For nearly all cases, Django's built-in template language is perfectly adequate. However, if the bottlenecks in your Django project seem to lie in the template system and you have exhausted other opportunities to remedy this, a third-party alternative may be the answer.
Jinja2 can offer performance improvements, particularly when it comes to speed.
Alternative template systems vary in the extent to which they share Django's templating language.
代替のソフトウェア実装Link to this heading
It may be worth checking whether Python software you're using has been provided in a different implementation that can execute the same code faster.
However: most performance problems in well-written Django sites aren't at the Python execution level, but rather in inefficient database querying, caching, and templates. If you're relying on poorly-written Python code, your performance problems are unlikely to be solved by having it execute faster.
Using an alternative implementation may introduce compatibility, deployment, portability, or maintenance issues. It goes without saying that before adopting a non-standard implementation you should ensure it provides sufficient performance gains for your application to outweigh the potential risks.
With these caveats in mind, you should be aware of:
PyPyLink to this heading
PyPy は Python 自身で書かれた Python 実装です ('標準の' Python 実装は C で書かれています)。heavyweight なアプリケーションの場合、PyPy を使用するとパフォーマンスが大幅に向上する可能性があります。
PyPy プロジェクトの主目的の1つは、既存の Python API とライブラリとの 互換性 です。Django は互換性がありますが、他の依存ライブラリの互換性については確認が必要です。
Python ライブラリの C 実装Link to this heading
Some Python libraries are also implemented in C, and can be much faster. They aim to offer the same APIs. Note that compatibility issues and behavior differences are not unknown (and not always immediately evident).