PHPコードのパフォーマンスを最適化する63 +のベストプラクティス

このエントリーをはてなブックマークに追加

notoです。

WEB+DB PRESSを読んでいたら、63+ best practice to optimize PHP code performancesが紹介されていたので、一部分だけ訳してみました。

 

  1. If a method can be static, declare it static. Speed improvement is by a factor of 4.
  2. echo is faster than print.(* compare with list from phplens by John Lim)
  3. Use echo’s multiple parameters instead of string concatenation.
  4. Set the maxvalue for your for-loops before and not in the loop.
  5. Avoid magic like __get, __set, __autoload
  6. require_once() is expensive
  7. Use full paths in includes and requires, less time spent on resolving the OS paths.
  8. See if you can use strncasecmp, strpbrk and stripos instead of regex
  9. str_replace is faster than preg_replace, but strtr is faster than str_replace by a factor of 4.
  10. Error suppression with @ is very slow.
  11. Turn on apache’s mod_deflate
  12. Close your database connections when you’re done with them
  13. $row[’id’] is 7 times faster than $row[id]
  14. Error messages are expensive

63+ best practice to optimize PHP code performances

 
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で確認できます。

間違ってたら指摘してください。

return top