Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Which is more efficient: a concatonated return variable, or returning each line individually?

I have a sytem where I want to build an HTML table in PHP from data retrieved from a databse.

I've previously used two different methods for creating the HTML and echoing it.

Building a return variable, and echoing at the end of the PHP script:

<?php
$data['category']['parts']; // format of the data

$retval = '<table>';
foreach($data as $category) {
  $retval .= '<tr>';
  foreach($category as $data) {
    $retval .= '<td>'.$data.'</td>'
  }
  $retval .= '</tr>';
}
$retval .= '</table>';

echo $retval;

The other method is to echo each line as the code comes to it:

<?php
$data['category']['parts']; // format of the data

echo '<table>';
foreach($data as $category) {
  echo '<tr>';
  foreach($category as $data) {
    echo '<td>'.$data.'</td>'
  }
  echo '</tr>';
}
echo '</table>';

Which of the two methods is more efficient, in terms of processor/memory usage, and also for processing speed? Is there actually a real difference, rather than just a question of style?

like image 897
Richard Kille Avatar asked Mar 15 '23 20:03

Richard Kille


1 Answers

My shot is: whatever you find more readable. Impact on performance is so small that probably you won't see any difference.

However, if you really care, echo should be faster (nothing better than a performance test on your specific scenario) because string concatenation will resize retval multiple times (and this will impact performance).

Even better you should avoid concatenation also in your echo:

<?php
$data['category']['parts']; // format of the data

echo '<table>';
foreach($data as $category) {
  echo '<tr>';
  foreach($category as $data) {
    echo '<td>', $data, '</td>';
  }
  echo '</tr>';
}
echo '</table>';

Do you want to do better? Just construct your own string builder object (but, honestly, gain is so small that you should seriously consider if worth your effort).

like image 89
Adriano Repetti Avatar answered Apr 07 '23 16:04

Adriano Repetti