はじめに
本稿は Android Developers のドキュメントの「Best Practices for Performance」内の「Performance Tips」と「Improving Layout Performance」の簡易'メモ'です。翻訳ではありませんので、詳細はリンク先のドキュメントを確認ください。
パフォーマンスチップス
原則
- 必要ないことはやらない
- 回避できるならメモリを割り当てない
Tips
-
必要ないオブジェクトは作らない
http://developer.android.com/training/articles/perf-tips.html#ObjectCreation -
フィールドにアクセスしないメソッドは static にする
http://developer.android.com/training/articles/perf-tips.html#PreferStatic -
定数には static final を使う
http://developer.android.com/training/articles/perf-tips.html#UseFinal -
クラス内でのフィールドへのアクセスに getter, setter を使わない
http://developer.android.com/training/articles/perf-tips.html#GettersSetters -
拡張 for 文を使う
http://developer.android.com/training/articles/perf-tips.html#Loops -
浮動小数点を使わない
http://developer.android.com/training/articles/perf-tips.html#AvoidFloat -
ライブラリを使いこなす
http://developer.android.com/training/articles/perf-tips.html#UseLibraries
(以降省略)
レイアウトパフォーマンスを改善する
レイアウト階層を最適化する
レイアウトを検査する
- Hierarchy Viewer というツールを使えばレイアウトパフォーマンスのボトルネックを検出できる
- hierarchyviewer は、<sdk>/tools/ から起動する
レイアウトを修正する
- narrow and deep ではなく、shallow and wide なレイアウトを作る
- layout_weight を使うときは慎重に
Lint を使う
- Lint ツールを使えばレイアウトの改善点を抽出できる
画像引用元:http://developer.android.com/training/improving-layouts/optimizing-layout.html#Lint
<include/> でレイアウトを再利用する
- <include> タグを使う
- android:layout_* 属性のパラメータはすべて上書きできる
- 上書きを有効にするには、必ず android:layout_height and android:layout_width を記述すること
- <merge> タグを使う
- <include> を使ってレイアウトを挿入する際、LinearLayout in LinearLayout のような冗長なレイアウト階層を回避できる
オンデマンドで View をロードする
- ViewStub は、必要なタイミングで描画を行うため、事前に View をロードするコストがかからない
- ViewStub には android:layout 属性が必要
- ViewStub をロードする場合、setVisibility(View.VISIBLE) or inflate() メソッドをコールする
スムーズにスクロールする ListView を作る
- スムーズにスクロールする ListView のポイントは、メインスレッドの処理を軽減すること
- UIの描画処理以外は、AsyncTask などを使用してバックグランドスレッドで処理を行う
- "view holder"デザインパターンを利用すれば、毎回 findViewById する必要がなくなる