比较php字符串连接的效率

php字符串连接有三种方式

1)使用 . 链接

2)使用 .= 连接

3)implode 函数连接数组元素

/*以下测试在ci框架进行*/
    private function get_mcrotime()
    {
            list($mic,$sec) = explode(" ",microtime());
            return ((float)$mic + (float)$sec);
    }

        public function test0(){
        //0.49530792236328
        //0.50851202011108
        //0.50111794471741

        $start = $this->get_mcrotime();
        define("num",100000);
        $str1 = 'ha';
        $str2 = '';
        for($i=0;$i<num;$i++){
            $str2 = $str2 . $str1;
        }
        echo $this->get_mcrotime()-$start;
    }
        
        public function test1(){
        //0.0046639442443848
        //0.0040309429168701
        $start = $this->get_mcrotime();
        define("num",100000);
        $str1 = 'ha';
        $str2 = '';
        for($i=0;$i<num;$i++){
            $str2 .= $str1;
        }
        echo $this->get_mcrotime()-$start;
    }

        public function test2(){
        //0.010957956314087
        //0.012393951416016
        $start = $this->get_mcrotime();
        define("num",100000);
        $str1 = 'ha';
        $str2 = '';
        $var = array();
        for($i=0;$i<num;$i++){
            array_push($var,$str1);
        }
        $str2 = implode($var);
        
        echo $this->get_mcrotime()-$start;
    }

从上述结果看出,使用 .= 链接字符串最为有效率, 而使用 . 链接最为耗时。

原文地址:https://www.cnblogs.com/hejun695/p/5387495.html