isset() vs strlen() - a fast/clear string length calculation

Viewed 12386

I came across this code...

if(isset($string[255])) {
    // too long
}

isset() is between 6 and 40 faster than

if(strlen($string) > 255) {
    // too long
}

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().

How can we use the faster isset() function while retaining readability of the code?

EDIT : test to show the speed http://codepad.org/ztYF0bE3

strlen() over 1000000 iterations 7.5193998813629
isset() over 1000000 iterations 0.29940009117126

EDIT2 : here's why isset() is faster

$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!';
}

This is faster than using strlen() because, “… calling a function is more expensive than using a language construct.” http://www.phpreferencebook.com/tips/use-isset-instead-of-strlen/

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... https://stackoverflow.com/questions/6983208/is-micro-optimisation-important-when-coding

7 Answers
Related