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, "."));

而且我真的不认为你分割这个字符串的方式会影响任何实际程序的性能。100 000 次迭代是相当巨大的...... ;-)

于 2009-11-05T21:33:59.837 回答
0
<?php
$iterations = 100000;
$fullhost = 'subdomain.domain.tld';

$start = microtime(true);

for($i = 0; $i < $iterations; $i++) 
{
    $vhost = substr($fullhost, 0, strpos($fullhost, '.'));
}

$total = microtime(true) - $start;
printf( 'extracted %s from %s %d times in %s seconds', $vhost, $fullhost, $iterations, number_format($total,5));
?>

在 0.44695 秒内从 subdomain.domain.tld 提取子域 100000 次

但那是在编码视频时,所以在更好的情况下它可能会更快。

于 2009-11-06T01:09:31.343 回答