Home > Backend Development > PHP Tutorial > Efficiency comparison of several string connections in PHP

Efficiency comparison of several string connections in PHP

高洛峰
Release: 2023-03-06 06:26:01
Original
1875 people have browsed it

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;
   
?>
Copy after login

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;
   
?>
Copy after login

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;
   
?>
Copy after login

Run 4 times, excluding the first running time, the three times are:

3.3184430599213

3.2759411334991
3.2663381099701

As can be seen from the above, string connection directly through . is the most inefficient.

The above article about the efficiency comparison (detailed explanation) of several string connections in PHP is all the content shared by the editor. I hope it can give you a reference, and I hope you will support the PHP Chinese website.

For more articles related to the efficiency comparison of several string connections in PHP, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template