PHP A more efficient way to judge the length of a string

  • 2021-01-18 06:22:09
  • OfStack

Experienced programmers have found that php determines the length of a string, and using isset() is faster and more efficient than strlen().
That is:


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

In a simple test with examples, the situation is basically true, isset() is almost 3 times more efficient than strlen().
Example:

<?php
 // use strlen way 
 $arr = "123456";
 $sTime = microtime(1);
 if(strlen($arr) > 6){
 // echo 1;
 }
 echo microtime(1) -  $sTime;

Output: 0.00035595893859863

<?php
// use isset($arr{}) way 
 $arr = "123456";
 $sTime = microtime(1);
 if(!isset($arr{6})){
 // echo "1\r\n";
 }
 echo microtime(1) - $sTime;

Output: 0.00019097328186035

Why is isset() faster than strlen()
The strlen() function executes fairly quickly because it does not do any calculations and only returns the known length of the string stored in the zval structure (C's built-in data structure for storing PHP variables). However, since strlen() is a function, it is somewhat slower because the function call goes through a number of steps, such as lowercase, hash lookup, and follows function 1 as it is called.
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 lookups and lowercase letters. That is, you don't really spend much overhead in the top-level code that verifies the length of the string.

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


Related articles: