Page MenuHomePhorge

[Performance] Avoid to calculate a string length, if we are just interested in "is empty"
Open, WishlistPublic

Description

IMPORTANT: There are a lot of cases where if(strlen($alien)) may have sense and may be even faster. This Task is ONLY about few different cases. Read the scope.

Scope of this Task:

  • the input variable is already strictly a string (its type is string)
    • its type is "string" and nothing else
    • No NULL. No alien things. No integer. No undefined. No object with __toString(). It must be a damn string.
    • for example a string can come from phutil_string_cast($v) or (string) $v

Take this counter example:

$v = phutil_string_cast($alien);
if (strlen($v)) {
  // Yeah! Non empty string!
}

When we are sure that we have a string, the strlen() may be confusing and overkill and can be simplified since we are not interested in the length of the string, and we are also not interested in any benefit coming from the internal cast-to-string applied to strlen() (that could be useful in some cases, but not here):

So in this exact circumstance we can just apply the proposed conversion, that is, checking if the string was not casted to an empty string:

$v = phutil_string_cast($alien);
if ($v !== '') {
  // Yeah! Non empty string!
}

We are aware that some persons may be interested in just adopting if($v) instead. But this is a well-known documented pitfall that causes the loss of the string "0", so we adopt this semplification only if we are 100% sure that the string 0 is totally nonsense:

$v = phutil_string_cast($alien);
if ($v) {
  // Yeah! Non empty string! And not "0"!
}

Example cases

In these few cases we can avoid strlen():