- 2006/11/21
- PHP
PHPをコーディング・設計する際に12個のことに気を使えば、もっと早くなるという記事があった。
- If a method can be static, declare it static. Speed improvement is by a factor of 4.
- 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.
- If you need to find out the time when the script started executing, $_SERVER[’REQUEST_TIME’] is preferred to time()
- See if you can use strncasecmp, strpbrk and stripos instead of regex
- preg_replace is faster than str_replace, but strtr is faster than preg_replace by a factor of 4
- If the function, such as string replacement function, accepts both arrays and single characters as arguments, and if your argument list is not too long, consider writing a few redundant replacement statements, passing one character at a time, instead of one line of code that accepts arrays as search and replace arguments.
- Error suppression with @ is very slow.
- $row['id'] is 7 times faster than $row[id]
- Error messages are expensive
- Do not use functions inside of for loop, such as for ($x=0; $x < count($array); $x) The count() function gets called each time.
PHP4ではClass化することは滅多にないので(1)〜(2)は無視するとして。
(3)の require_once()が遅い(というかメモリを消費するという意味かな)というのは気になる。include_once()のが良いってことなのかな。
さらに(4)で、インクルードするパスは絶対パスが有利…と。まぁ、これは当然かな。
普通はインクルードするディレクトリを define() で定義して、include_once(INCLUDE_DIR . "xxx.php"); とかってやるのが良い感じ。
(5)は気にしない。
(6)の正規表現よりも strncasecmp() / strpbrk() / stripos() を使えっていうのは、理解できるんだけど、正規表現が楽すぎて、ついつい早さよりも優先してしまうなぁ。
(7)は strtr() >> preg_replace() > str_replace()。str_replace() よりも preg_replace() の方が早いっていうのは意外。単純な置換の時は strtr() を使えってことか。
(8)はちょっと理解できなかった。配列か配列じゃないかを自動で判定させるのは良くない…?ってことか。
(9)は関係ないのでパス。今時いるのかな、@でエラー制御する人。
(10)は有名な話。配列のキーを、シングルクオートで囲む・ダブルクオートで囲む・なにも囲まないでは、処理スピードが違う。シングル > ダブル > 囲まない の順番。ただ、実験してみると大きいスクリプトでない限り差は顕著に見られない。けど、可読性とバグ・エラー潰しのために囲っておくが吉。
(11)は、PHPのエラーメッセージは重いよって話。本番環境なら当然。
(12)は、PHPに限らず色々な言語に共通する。for() で毎回計算しなくてはならない場所に、さらに関数を入れて計算させると遅くなるよ、と。for() で回す前に、あらかじめ計算して数値を出してから。
ほとんど基本的なことだけど、こういう地道な気配りがパフォーマンスの向上につながる…と思う。設計さえ良ければ。
- Newer: MOTHER3i
- Older: 写真素材サイトまとめ