Home > Backend Development > PHP Tutorial > Detailed explanation of efficiency comparison examples of three types of string connections in PHP

Detailed explanation of efficiency comparison examples of three types of string connections in PHP

伊谢尔伦
Release: 2023-03-11 16:06:01
Original
1404 people have browsed it

There are roughly three types of String connections in php:

1. Use . to connect directly.

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, three times The times are:

22.165272951126
22.003527164459
22.15947508812

The second method code 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 is the detailed content of Detailed explanation of efficiency comparison examples of three types of string connections in PHP. For more information, please follow other related articles on 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