代码之家  ›  专栏  ›  技术社区  ›  Renato Aquino

有什么方法可以更快地提取字符串?

  •  0
  • Renato Aquino  · 技术社区  · 16 年前

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

    因此,时间安排:

    While   :0.0886390209198
    Regex   :1.22981309891
    Substr  :0.338994979858
    Explode :0.450794935226
    Replace :0.33411693573
    
    3 回复  |  直到 16 年前
        1
  •  5
  •   Ville Laurikari    16 年前

    您可以尝试使用strtok()函数:

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

    它比while循环的正确版本快,

        2
  •  3
  •   Alex    16 年前

    我会用substr()的方法。

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

    我真的不认为分割字符串的方式会影响任何实际程序的性能。100000次迭代是相当大的…;-)

        3
  •  0
  •   Kris    16 年前
    <?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次

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