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
In modern ObjectOriented Web Applications a single line that you write within a small Class easily can be run several 100s of times to build a single Web Page.
You might want to profile your Web Site with XDebug and you might be surprised how many times each Method of a Class is executed.
Then in real world scenarios you might not work only with little strings but also with really big documents up to 3MB size or larger.
You might also come across text with non latin characters.
So eventually what was initially just a little performance loss might result in serveral 100s of milliseconds on a Web Page Rendering.
So I am very interested in this issue and wrote a little test that would test 4 different Methods to check whether a string is really empty "" or does actually contain something like "0".
I found that PHP as a hard time to work with non latin characters to I copied a russian text from a Web Page to compare the results between the tiny string "0" and the bigger russian text.
To see really a difference I called each test function several millions of times.
Test Results
Conclusion
emtpy()
Function performs well but fails on strings like "0".mb_strlen()
Function which is necessary to check on texts with non latin characters performs worse on larger texts.$string !== ""
performs very well. Even better than theempty()
Function.isset($string[0])
Check.I will definitely have to work over my whole Object Library.
If you want to keep clarity you could do something like: