PHP Performance Optimizations: Use Isset () to determine string length faster than strlen ()
How to determine the length of a string in PHP?
The first thing many people think about is strlen () Mb_strlen () these functions.
But in terms of program performance, these two functions are not optimal in judging the length of a string, although they are professional-level functions for detecting string lengths. Through my practice summary, PHP judge the length of the string, using Isset () at a faster speed than strlen (), more efficient execution.
So why is isset () faster than strlen ()?
The strlen () function function executes quite quickly because it does not do any calculations and only returns the length of the known string stored in the Zval structure (the built-in data structure of C for storing PHP variables). However, because strlen () is a function, it is somewhat slower because function calls go through a number of steps, such as lowercase letters, hash lookups, which are executed with the called function. So in some cases, reasonable use of isset () can speed up your program. Because Isset () is a language structure, its execution does not require function lookups and lowercase letters.
Determine string lengths by Isset () and strlen ()
Examples are as follows:
$str = ' http://www.scutephp.com/';
if (strlen ($STR) <5) {echo "is under 5";}
if (!isset ($str {5})) {echo "is under 5";}
Let's examine the two functions of strlen () and isset () in detail.
The PHP strlen () function defines and uses the strlen () function to return the length of a string.
Syntax: strlen (String) parameter: string
Description: Required. Specifies the string to check.
Strlen () Function instance
Echo strlen ("Hello world!");
?>
The PHP isset () function Isset function is to detect whether a variable is set.
Syntax: bool Isset (mixed var [, mixed Var [, ...])
Return value: Returns FALSE if the variable does not exist
Returns FALSE if the variable exists and its value is null
Returns TURE if the variable exists and the value is not NULL
Returns TRUE if each item meets the previous requirement when checking multiple variables at the same time, otherwise the result is FALSE
If a variable has been freed with unset (), it will no longer be isset ().
If you use Isset () to test a variable that is set to NULL, FALSE is returned.
Also note that a null byte ("") is not equivalent to PHP's null constant.
Warning: isset () can only be used for variables, because passing any other parameter will result in parsing errors. To detect if a constant is set, use the defined () function.