Currently token_replace() still continues to execute even if it doesn't find any tokens to generate/replace in the text.

We should add a return if token_replace() is empty.

Before:

function token_replace($text, array $data = array(), array $options = array()) {
  $replacements = array();
  foreach (token_scan($text) as $type => $tokens) {
    $replacements += token_generate($type, $tokens, $data, $options);
    if (!empty($options['clear'])) {
      $replacements += array_fill_keys($tokens, '');
    }
  }

  // Optionally alter the list of replacement values.
  if (!empty($options['callback']) && function_exists($options['callback'])) {
    $function = $options['callback'];
    $function($replacements, $data, $options);
  }

  $tokens = array_keys($replacements);
  $values = array_values($replacements);

  return str_replace($tokens, $values, $text);
}

After:

function token_replace($text, array $data = array(), array $options = array()) {
  $scanned_tokens = token_scan($text);
  if (empty($scanned_tokens)) {
    return $text;
  }

  $replacements = array();
  foreach ($scanned_tokens as $type => $tokens) {
    $replacements += token_generate($type, $tokens, $data, $options);
    if (!empty($options['clear'])) {
      $replacements += array_fill_keys($tokens, '');
    }
  }

  // Optionally alter the list of replacement values.
  if (!empty($options['callback']) && function_exists($options['callback'])) {
    $function = $options['callback'];
    $function($replacements, $data, $options);
  }

  $tokens = array_keys($replacements);
  $values = array_values($replacements);

  return str_replace($tokens, $values, $text);
}

Comments

dave reid’s picture

Assigned: Unassigned » dave reid
dave reid’s picture

Title: Improve performance of token_replace() if token_scan() returns an empty array » Improve performance of token_replace() if there are no tokens to replace
dave reid’s picture

Status: Active » Needs review
StatusFileSize
new677 bytes
dave reid’s picture

With a test.

Status: Needs review » Needs work

The last submitted patch, 1346166-token-replace-performance-no-tokens.patch, failed testing.

dave reid’s picture

Status: Needs work » Needs review
StatusFileSize
new1.29 KB

Try that again.

sun’s picture

Status: Needs review » Reviewed & tested by the community

Excellent!

sun’s picture

tstoeckler’s picture

Too scared to un-RTBC a patch by Dave Reid reviewed by sun :), but I think this would be a very valid place for a comment. If you look at the "before" function in the op without the context of this issue, then you think nothing is wrong (at least I did...).

dries’s picture

Status: Reviewed & tested by the community » Fixed

Committed to 8.x and back-ported to 7.x.

Status: Fixed » Closed (fixed)

Automatically closed -- issue fixed for 2 weeks with no activity.

cweagans’s picture

Issue tags: +Needs backport to D7