PHPコードのパフォーマンスを最適化する63 +のベストプラクティス
notoです。
WEB+DB PRESSを読んでいたら、63+ best practice to optimize PHP code performancesが紹介されていたので、一部分だけ訳してみました。
- If a method can be static, declare it static. Speed improvement is by a factor of 4.
- echo is faster than print.(* compare with list from phplens by John Lim)
- Use echo’s multiple parameters instead of string concatenation.
- Set the maxvalue for your for-loops before and not in the loop.
- Avoid magic like __get, __set, __autoload
- require_once() is expensive
- Use full paths in includes and requires, less time spent on resolving the OS paths.
- See if you can use strncasecmp, strpbrk and stripos instead of regex
- str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4.
- Error suppression with @ is very slow.
- Turn on apache’s mod_deflate
- Close your database connections when you’re done with them
- $row[’id’] is 7 times faster than $row[id]
- Error messages are expensive
1.メソッドを静的にできるのなら、staticと宣言する。4倍の速度に向上される。
2.echoの方がprintより速い
3.文字列を連結させるより、echoに複数パラメータを渡したほうがいい
こっちよりも
<?php echo $foo . $bar;
こっちのがいいってことですかね。
<?php echo $foo,$bar;
4.forループ文で、カウントはループの外で行う
こっちよりも
<?php for($i=0; $i<count($arr); $i++){}
こっち
<?php $count = count($arr); for($i=0; $i<$count; $i++){}
5.__get, __set, __autoloadのようなマジックメソッドの使用を避ける
6.require_once()は重すぎ
7.includes、requiresは絶対パス指定する
8.正規表現の替わりにstrncasecmp、strpbrk、striposが使用できるか確認する
9.preg_replaceよりstr_replaceの方が速い。strtrの方がstr_replaceより4倍速い
10.エラー制御演算子はめっさ遅い
11.apacheのdeflateモジュールを有効にする
12.データベースの処理が終了したら、コネクションをクローズする
13.$row[’id’]は$row[id]より7倍速い
14.(PHPの)エラーメッセージは重すぎ
結構知らないのもありますねー。それよりも英語読めなすぎlang-8でもやろうかしら。
続きは63+ best practice to optimize PHP code performancesで確認できます。
間違ってたら指摘してください。
コメント 0