title: isset() vs strlen() - a fast/clear string length calculation
body: <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="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="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>