0

HTTP リクエストの仮想ホスト名を抽出する必要があります。これはリクエストごとに行われるため、これを行う最速の方法を探しています。

次のコードと時間は、私が研究した方法のほんの一部です。

それで、これを行うためのより速い方法はありますか?

$hostname = "alphabeta.gama.com";

$iteractions = 100000;

//While Test

$time_start = microtime(true);
for($i=0;$i < $iteractions; $i++){
    $vhost = "";
    while(($i < 20) && ($hostname{$i} != '.')) $vhost .= $hostname{$i++};
}

$time_end = microtime(true);
$timewhile = $time_end - $time_start;

//Regexp Test
$time_start = microtime(true);
for($i=0; $i<$iteractions; $i++){
    $vhost = "";
    preg_match("/([A-Za-z])*/", $hostname ,$vals);
    $vhost = $vals[0];
}
$time_end = microtime(true);
$timeregex = $time_end - $time_start;

//Substring Test
$time_start = microtime(true);
for($i=0;$i<$iteractions;$i++){
    $vhost = "";
    $vhost = substr($hostname,0,strpos($hostname,'.'));
}
$time_end = microtime(true);
$timesubstr = $time_end - $time_start;

//Explode Test
$time_start = microtime(true);
for($i=0;$i<$iteractions;$i++){
    $vhost = "";
    list($vhost) = explode(".",$hostname);
}
$time_end = microtime(true);
$timeexplode = $time_end - $time_start;

//Strreplace Test. Must have the final part of the string fixed.
$time_start = microtime(true);
for($i=0;$i<$iteractions;$i++){
    $vhost = "";
    $vhost = str_replace(".gama.com","",$hostname);
}
$time_end = microtime(true);
$timereplace = $time_end - $time_start;

echo "While   :".$timewhile."\n";
echo "Regex   :".$timeregex."\n";
echo "Substr  :".$timesubstr."\n";
echo "Explode :".$timeexplode."\n";
echo "Replace :".$timereplace."\n";

そして結果のタイミングとして:

一方:0.0886390209198
正規表現:1.22981309891
サブストリング:0.338994979858
爆発:0.450794935226
置換:0.33411693573
4

3 に答える 3

5

strtok()関数を試すことができます:

$vhost = strtok($hostname, ".")

これは、whileループの正しいバージョンよりも高速で、はるかに読みやすくなっています。

于 2009-11-05T21:23:20.910 に答える
3

私はそれをsubstr()の方法で行います。

$vhost = substr($host, 0, strstr($host, "."));

そして、この文字列をどのように分割するかが、実際のプログラムのパフォーマンスに影響を与えるとは思いません。100000回の反復は非常に巨大です...;-)

于 2009-11-05T21:33:59.837 に答える