Note that there are some explanatory texts on larger screens.

plurals
  1. POisset() vs strlen() - a fast/clear string length calculation
    primarykey
    data
    text
    <p>I came across this code...</p> <pre><code>if(isset($string[255])) { // too long } </code></pre> <p>isset() is between 6 and 40 faster than </p> <pre><code>if(strlen($string) &gt; 255) { // too long } </code></pre> <p>The only drawback to the isset() is that the code is unclear - we cannot tell right away what is being done (see pekka's answer). We can wrap isset() within a function i.e. strlt($string,255) but we then loose the speed benefits of isset().</p> <p><strong>How can we use the faster isset() function while retaining readability of the code?</strong> </p> <p>EDIT : test to show the speed <a href="http://codepad.org/ztYF0bE3" rel="nofollow noreferrer">http://codepad.org/ztYF0bE3</a></p> <pre><code>strlen() over 1000000 iterations 7.5193998813629 isset() over 1000000 iterations 0.29940009117126 </code></pre> <p>EDIT2 : here's why isset() is faster</p> <pre><code>$string = 'abcdefg'; var_dump($string[2]); Output: string(1) “c” $string = 'abcdefg'; if (isset($string[7])){ echo $string[7].' found!'; }else{ echo 'No character found at position 7!'; } </code></pre> <p>This is faster than using strlen() because, “… calling a function is more expensive than using a language construct.” <a href="http://www.phpreferencebook.com/tips/use-isset-instead-of-strlen/" rel="nofollow noreferrer">http://www.phpreferencebook.com/tips/use-isset-instead-of-strlen/</a></p> <p>EDIT3 : I was always taught to be interested in mirco-optimisation. Probably because I was taught at a time when resources on computers were tiny. I'm open to the idea that it may not be important, there are some good arguments against it in the answers. I've started a new question exploring this... <a href="https://stackoverflow.com/questions/6983208/is-micro-optimisation-important-when-coding">https://stackoverflow.com/questions/6983208/is-micro-optimisation-important-when-coding</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload