Heim  >  Artikel  >  Backend-Entwicklung  >  PHP字符串单字气节作——substr真的好慢

PHP字符串单字气节作——substr真的好慢

WBOY
WBOYOriginal
2016-06-13 11:01:31859Durchsuche

PHP字符串单字节操作——substr真的好慢

当我们要操作字符串中的某一个单字节时,我们该使用什么样的方式操作?一直以为,substr函数不会很慢。但今天测试了一下,结果并非如此。以下是测试代码:

?

<?php    $str='abcdefghijklmnopqrstuvwxyz1234567890';    error_reporting(E_ALL);    /**     * Simple function to replicate PHP 5 behaviour     */    function microtime_float()    {        list($usec, $sec) = explode(" ", microtime());        return ((float)$usec + (float)$sec);    }    //使用substr函数    $start=microtime_float();    for ($k = 100; $k > 0; $k--) {         for ($i=0;$i<strlen($str);$i++)           echo substr($str,$i,1), ' ';    }    $end = microtime_float();    echo("<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/> t i m e :" .  round( $end - $start ,6) ."<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>");       //使用字节操作    $start=microtime_float();    for ($k = 100; $k > 0; $k--) {           for ($i=0;$i<strlen($str);$i++)           echo $str{$i}, ' ';    }   $end = microtime_float();    echo("<br/> <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>t i m e :" .  round( $end - $start ,6) ."<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>");            //使用数组模式操作    $start=microtime_float();    for ($k = 100; $k > 0; $k--) {            for ($i=0;$i<strlen($str);$i++)           echo $str[$i], ' ';    }    $end = microtime_float();    echo("<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/> t i m e :" .  round( $end - $start ,6) ."<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>");        ?>

?以下是测试结果:

t i m e :0.003782
t i m e :0.002862
t i m e :0.002587

t i m e :0.00351
t i m e :0.002649
t i m e :0.002786

由此可见,substr速度是很慢的。而字节操作与数组操作模式,则是同一级别的。由此我们认为,如果对字符串进行字节操作,则使用字节操作模式最好,因为,这一方式不会导致误以为变量类型是数组。
当然,这种操作方式有其局限性,那就是对于中文字串是无法这样处理的,你只有使用mb_substr!!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn