Home  >  Article  >  Backend Development  >  A more efficient way to determine the length of a php string

A more efficient way to determine the length of a php string

怪我咯
怪我咯Original
2017-07-04 11:51:181940browse

In php, when we need to determine the length of a string, the first thing we think of is strlen()function, yes, strlen() returns It is the length of the string, so there is no problem in using it this way. However, from the perspective of PHP program optimization, using strlen() to determine the length of a string is probably the best way to write it

Experienced programmers have found that when PHP determines the length of a string, use isset() It is faster than strlen() and has higher execution efficiency.
That is:

The code is as follows:

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


After a simple test with an example, the situation is basically true. The efficiency of isset() is almost strlen () 3 times.
Example:

The code is as follows:

 6){
 // echo 1;
 }
 echo microtime(1) -  $sTime;

Output:0.00035595893859863

The code is as follows :

Output: 0.00019097328186035

isset() is faster than strlen()
strlen() function function execution Pretty fast because it doesn't do any calculations and just returns the known string length stored in the zval structure (C's built-in data structure used to store 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() technique 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().

The above is the detailed content of A more efficient way to determine the length of a php string. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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