LoginSignup
4
0

More than 5 years have passed since last update.

【PHP】単純な文字列検索を行うならstrposを使おう

Posted at

単純な文字列検索であればstrposが高速であるということですが、どれくらい違うのか検証してみました。

対象関数

検証

search.php
<?php

$word = 'hogehoge';

$start = microtime(true);
for ($i=0; $i < 10000000; $i++) {
    preg_match('/hoge/', $word);
}
$end = microtime(true);
$elapsed = $end - $start;
echo "preg_match:time = " . $elapsed . "[sec]" . PHP_EOL;

$start = microtime(true);
for ($i=0; $i < 10000000; $i++) {
    strstr('hoge', $word);
}
$end = microtime(true);
$elapsed = $end - $start;
echo "strstr:time = " . $elapsed . "[sec]" . PHP_EOL;

$start = microtime(true);
for ($i=0; $i < 10000000; $i++) {
    strpos('hoge', $word);
}
$end = microtime(true);
$elapsed = $end - $start;
echo "strpos:time = " . $elapsed . "[sec]" . PHP_EOL;
$ php search.php
preg_match:time = 2.2518329620361[sec]
strstr:time = 0.7945499420166[sec]
strpos:time = 0.43859314918518[sec]
4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0