implode() vs substr()

Asked

Viewed 111 times

2

Taking into account the codes below:

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

and that

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

Taking performance into account, which form will have the least 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 found nothing, in the PHP manual about implode() and subter() only shows usage detailing.

At this link says making implode "usually takes twice as long as the standard concatenation operator", but substr() would also have to traverse the string to make the cut, correct?

Related: Explanation about concatenation of variables in PHP

1 answer

2


According to a test I did, the first option is more efficient. I tested your code using microtime and it turns out, 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: https://stackoverflow.com/questions/18826797/php-listexplode-vs-substrstrpos-what-is-more-efficient

Browser other questions tagged

You are not signed in. Login or sign up in order to post.