Home > Article > Backend Development > Efficiency comparison of several string connections in PHP
php has roughly three types of string connections:
#1. Directly use . to connect.
2. Use .= to connect.
3. First push into the array, and then connect through the join function.
The efficiency of these three methods are tested below:
The code of the first method is as follows:
<?php function get_tm() { list ( $usec, $sec ) = explode ( " ", microtime () ); return (( float ) $usec + ( float ) $sec); } $temp="test"; $result=""; define("num",100000); $start=get_tm(); for($i=0;$i<num;$i++) { $result=$result.$temp; } echo get_tm()-$start; ?>
Run 4 times, excluding the first running time, the three times are:
22.165272951126
22.003527164459
22.15947508812
The code for the second method is as follows:
<?php function get_tm() { list ( $usec, $sec ) = explode ( " ", microtime () ); return (( float ) $usec + ( float ) $sec); } $temp="test"; $result=""; define("num",100000); $start=get_tm(); for($i=0;$i<num;$i++) { $result.=$temp; } echo get_tm()-$start; ?>
Run 4 times, excluding the first running time , the three times are:
3.1967310905457
3.1296961307526
3.0872850418091
##The third method code is as follows:
<?php function get_tm() { list ( $usec, $sec ) = explode ( " ", microtime () ); return (( float ) $usec + ( float ) $sec); } $temp="test"; $result=""; $arr=array(); define("num",100000); $start=get_tm(); for($i=0;$i<num;$i++) { array_push($arr, $temp); } $result=join($arr); echo get_tm()-$start; ?>Run 4 times, excluding the first running time, the three times are: 3.3184430599213
3.2759411334991
3.2663381099701