implode () vs substr ()

2

Considering the codes below:

$str = '';
for ($i = 30000; $i > 0; $i--) {
    $str .= 'STRING QUALQUER, ';
}
$str = subtr($str,0,-2);

and this

$sArr = array();
for ($i = 30000; $i > 0; $i--) {
    $sArr[] = 'STRING QUALQUER';
}
$str = implode(", ",$sArr);

Considering the performance, what form will have the lowest processing cost?

I found in a legacy code these two ways to do the same thing.

memory_limit is a factor? through my search I did not find anything, in the PHP manual about implode () and subtr () only shows usage detail.

says that doing " implode usually takes two times more than the standard concatenation operator ", but substr () would also have to go through the string to make the cut, right?

Related: Explanation of concatenation of variables in PHP

    
asked by anonymous 19.03.2018 / 23:08

1 answer

1

According to a test that I did, the first option is more efficient. I tested your code using microtime and apparently the first test takes less time to process.

The code used was:

function microtime_float() {
  list($usec, $sec) = explode(" ", microtime());
  return ((float)$usec + (float)$sec);
}

$time_start = microtime_float();

$str = '';
for ($i = 30000; $i > 0; $i--) {
    $str .= 'STRING QUALQUER, ';
}

$str = substr($str,0,-2);

$time_end = microtime_float();
$time_end_1 = $time_end - $time_start;

echo "A primeira solução levou $time_end_1 segundos.\n";

$time_start = microtime_float();

$sArr = array();
for ($i = 30000; $i > 0; $i--) {
    $sArr[] = 'STRING QUALQUER';
}

$str = implode(", ",$sArr);

$time_end = microtime_float();
$time_end_2 = $time_end - $time_start;

echo "A segunda solução levou $time_end_2 segundos.\n";

if($time_end_1 > $time_end_2) {
  echo 'O script 2 é mais rápido.';
} else {
  echo 'O script 1 é mais rápido.';
}

Source: link

    
20.03.2018 / 03:24