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

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

怪我咯
Release: 2023-03-12 14:22:02
Original
2098 people have browsed it

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})
Copy after login


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:

<?php
 //使用strlen方式
 $arr = "123456";
 $sTime = 
microtime
(1);
 if(strlen($arr) > 6){
 // echo 1;
 }
 echo microtime(1) -  $sTime;
Copy after login

Output:0.00035595893859863

The code is as follows :

<?php
//使用isset($arr{})方式
 $arr = "123456";
 $sTime = microtime(1);
 if(!isset($arr{6})){
 // echo "1\r\n";
 }
 echo microtime(1) - $sTime;
Copy after login

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!

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