Home > Backend Development > PHP Tutorial > A more efficient way to determine string length in PHP_PHP Tutorial

A more efficient way to determine string length in PHP_PHP Tutorial

WBOY
Release: 2016-07-13 10:36:57
Original
802 people have browsed it

Experienced programmers have found that using isset() in PHP to determine the string length is faster than strlen() and has higher execution efficiency.
That is:

Copy code The code is as follows:

$str = 'aaaaaa';
if(strlen($str) > 6)
VS
if(!isset($str{6})

A simple test with an example, the situation is basically true , isset() is almost 3 times more efficient than strlen()
Example:
Copy code The code is as follows:

//Use strlen method
$arr = "123456";
$sTime = microtime(1);
if(strlen($arr) > 6){
// echo 1;
}
echo microtime(1) - $sTime;

Output: 0.00035595893859863
Copy code The code is as follows:

//Use isset($arr{}) method
$arr = "123456";
$sTime = microtime(1);
if(!isset($arr{6})){
// echo "1rn";
}
echo microtime(1) - $sTime;

Output: 0.00019097328186035

Why isset() is faster than strlen()
strlen() function executes quite quickly because it does not do any calculations and only returns the data in the zval structure (C’s built-in data Structure used to store known string lengths stored in PHP variables). However, since strlen() is a function, it will be somewhat slow, because the function call will go through many steps, such as lowercase letters (Annotation: refers to the lowercase function name, PHP does not distinguish between uppercase and lowercase function names), hash search, Will be executed together with the called function.
In some cases, using the isset() trick can speed up the execution of your code. Because isset() is a language construct, it means that its execution does not require function lookup and letter lowercase. That is, you actually don't spend much overhead in the top-level code checking the string length.

So calling isset() is faster than strlen().

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/736830.htmlTechArticleExperienced programmers have found that using isset() in PHP to determine the length of a string is faster than strlen() Faster and more efficient execution. That is: Copy the code The code is as follows: $str = ‘aaaaaa’; if(...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template