What is the effectiveness of strlen () in PHP?

Does strlen number of bytes in the string by iterating over the string, or simply returning the value of the already calculated string length from the index?

The reason for my question is because I have the choice to store pre-computed values โ€‹โ€‹of very long lines for a speed-sensitive script, or I could just use the strlen function and save the encoding time.

But I would like to know how strlen works, since I tend to rely on it a lot, and maybe this is not a good idea?

UPDATE

See my test below.

+4
source share
1 answer

Screw it, I did a test:

 <?php $shortstring='hello'; $longstring='long'; for($run=0;$run<100000;$run++) $longstring.='dsffghdgfhdsda'.rand(1000,2000); $time=microtime(true); for($run=0;$run<100000000;$run++) $temp=strlen($shortstring); $time=microtime(true)-$time; echo "strlen on short string took $time seconds\n"; $time=microtime(true); for($run=0;$run<100000000;$run++) $temp2=strlen($longstring); $time=microtime(true)-$time; echo "strlen on long string took $time seconds\n"; 

results

 strlen on short string took 12.508891820908 seconds strlen on long string took 11.897696971893 seconds 

It does not explicitly iterate over the string, but returns a pre-indexed value. No speed difference.

+5
source

All Articles