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

Source: Internet
Author: User
Tags lowercase strlen

  in PHP when you need to judge a string length, the first thing we think of is the strlen () function, well, strlen () returns the length of the string, so there is no problem with it. However, it would be best to use strlen () to determine the length of a string from the point of view of the PHP program optimization

Experienced programmers found that PHP judged the length of the string, using Isset () faster than strlen () and executing more efficiently. namely:     code as follows: $str = ' aaaaaa '; if (strlen ($STR) > 6) VS if (!isset ($str {6})   With the example simple test, the situation is basically true, isset () efficiency is almost 3 times times that of strlen (). Example:   code is as follows: <?php  //use strlen mode   $arr = "123456";   $sTime = microtime (1);  if (strlen ($arr) > 6) { //echo 1;  }  echo microtime (1)-  $sTime;   Output: 0.00035595893859863   Code as follows: <?php//Use Isset ($arr {}) way   $arr = "123456";   $sTime = microtime (1);  if (!isset ($arr {6})) { //echo "1rn";    echo microtime (1)-$sTime;   Output: 0.00019097328186035   isset () speed is faster than strlen () strlen () function function is performed fairly quickly because it does not do any calculations and returns only the built-in data structure of the Zval struct (c). The length of the known string stored in the PHP variable to store. However, since strlen () is a function, it will be somewhat slower, because function calls go through a number of steps, such as lowercase letters, PHP is case-insensitive, and hash lookups follow the functions that are called. In some cases, using the isset () technique can speed up the execution of your code. Because with Isset () as a language structure, it means that its execution does not require function lookup and letter lowercase. That is, you're actually not spending too much on the top-level code that verifies the length of the string.   therefore calls Isset () faster than strlen ().
Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

11.11 Big Sale for Cloud

Get Unbeatable Offers with up to 90% Off,Oct.24-Nov.13 (UTC+8)

Get It Now >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.