strposとstrstrの速度比較

ある文字列の中で特定の文字列が現れるかどうかを調べる...ってんで色々と関数マニュアルを読み返していたら、strstrのページに

注意: もし特定の haystack に needle があるかどうかを調べるだけの場合、 より高速でメモリ消費も少ない strpos() を代わりに使用してください。

と注意書きがあったので実際の速度を調べてみる事にしました。テストに使う文字列はジョブズのあの有名な講演から以下の部分。自分が何になりたいかという直感に従うべし...という好きな一節です。

Your time is limited, so don't waste it living someone else's life. Don't be trapped by dogma─which is living with the results of other people's thinking. Don't let the noise of others opinions drown out your own inner voice. And most important, have the courage to follow your heart and intuition. They somehow already know what you truly want to become. Everything else is secondary.

この文字列からdogmaという単語が存在するかどうかを調べる処理を10000回行った時の平均値を取りました。ついでなので、大文字小文字を無視する場合や(自明ですが)正規表現でも確認。strpos, stripos, strstr, stristr, preg_match, preg_match(正規表現のiオプション付き)の6パターンで、結果は以下。(速い順)

関数時間(s)
strpos0.03461
strstr0.03685
preg_match0.04774
preg_match(iオプション付)0.04853
stripos0.07025
stristr0.07256

文字列内に特定文字列が出現するかどうかのチェックはstrposを使いましょう....ってまぁ予想通りの結果となりました。

あ、マニュアルにも記載はありますが、strposの返値を使って出現しない条件式を書く場合は !== false を使いましょう。== 0 にすると特定文字列が先頭にきてた場合にハマります。