我需要提取 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