Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- PHP foreach performance when adding string to variable
- foreach($data as $r=>$d)
- {
- $return = $return. "<tr>
- <td>
- ".$d["client_id"]."
- </td>
- ......
- <td>
- ".$d["date_stamp"]."
- </td>
- </tr>";
- }
- }
- foreach($data as $r=>$d)
- {
- $now= "<tr>
- <td>
- ".$d["client_id"]."
- </td>
- ......
- <td>
- ".$d["date_stamp"]."
- </td>
- </tr>";
- $return = $return.$now;
- }
- //////////function to get time
- function parsemicrotime(){
- list($usec, $sec) = explode(" ",microtime());
- return ((float)$usec + (float)$sec);
- }
- ////////////define test array
- $a = array();
- for($i = 0; $i < 5000; $i ++)//generate 5k rows
- {
- for($k=0; $k<5;$k++)//lets have just 6 columns
- {
- $a[$i]["column_".$k] = 'test string '.$i.' / '.$k.' - note that the size of the $output string makes a huge difference ';
- }
- }
- ///////////////first test
- $time_start = parsemicrotime();
- $output = '';
- foreach($a as $row=>$columns)
- {
- $output = $output ."
- <tr>
- <td>".$columns["test_0"]. "</td>
- <td>" .$columns["test_1"]. "</td>
- <td>" .$columns["test_2"]. "</td>
- <td>" .$columns["test_3"]. "</td>
- <td>" .$columns["test_4"]. "</td>
- <td>" .$columns["test_5"]. "</td>
- </tr>";
- }
- $approach_1_result = parsemicrotime()-$time_start;
- /////////////second test
- $time_start2 = parsemicrotime();
- $output2 = '';
- foreach($a as $row2=>$columns2)
- {
- $now2= "
- <tr>
- <td>".$columns["test_0"]. "</td>
- <td>" .$columns["test_1"]. "</td>
- <td>" .$columns["test_2"]. "</td>
- <td>" .$columns["test_3"]. "</td>
- <td>" .$columns["test_4"]. "</td>
- <td>" .$columns["test_5"]. "</td>
- </tr>";
- $output2 = $output2 .$now2;
- }
- $approach_2_result = parsemicrotime()-$time_start2;
- /////////////third test
- $time_start3 = parsemicrotime();
- ob_start();
- $output3 = '';
- foreach($a as $row3=>$columns3)
- {
- echo "
- <tr>
- <td>".$columns["test_0"]. "</td>
- <td>" .$columns["test_1"]. "</td>
- <td>" .$columns["test_2"]. "</td>
- <td>" .$columns["test_3"]. "</td>
- <td>" .$columns["test_4"]. "</td>
- <td>" .$columns["test_5"]. "</td>
- </tr>";
- }
- $output3 = ob_get_clean();
- $approach_3_result = parsemicrotime()-$time_start3;
- die("first test:".$approach_1_result."<br>second test:".$approach_2_result."<br>third test:".$approach_3_result);
- $a = [];
- for($i = 0; $i < 10000; $i ++)
- $a[] = $i;
- $output = '';
- foreach($a as $k => $v)
- $output = $output . "some static text" . $v . "some other text";
- $output .= 'some static text' . $v . 'some other text';
- $output = '';
- ob_start();
- foreach($a as $k => $v)
- echo 'some static text' . $v . 'some other text';
- $output = ob_get_clean();
- ob_start();
- foreach($data as $r=>$d)
- {
- echo "<tr>
- <td>
- ";
- echo $d["client_id"];
- echo "</td>
- ......
- <td>
- ";
- echo $d["date_stamp"];
- echo "</td>
- </tr>";
- }
- $return .= ob_get_contents();
- ob_end_clean();
Add Comment
Please, Sign In to add comment