6

Does using strlen actually count the number of bytes in the string by iterating through the string, or does it simple return the value of an already calculated length of the string from an index?

The reason for my question is because I have a choice to store pre-calculated values of very long strings for a speed-sensitive script, or I could just use the strlen function and save myself coding time.

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

UPDATE

See my benchmark below.

Alasdair
  • 13,348
  • 18
  • 82
  • 138
  • 1
    It is O(1) - it is *not* like a C string, which is O(n). –  Mar 02 '13 at 07:02
  • 1
    I can't find any documentation confirming it, but I'm pretty sure it's precalculated. PHP strings aren't modifiable, like C strings are. – Barmar Mar 02 '13 at 07:02
  • PHP is open source, you could check the code.... – Barmar Mar 02 '13 at 07:05
  • @Barmar Mutability has nothing to do with it. Ruby strings are modifiable and still have a discreet length. Also, not all valid C strings refer to objects that can be modified. –  Mar 02 '13 at 07:07
  • Whats about `mb_strlen()`? – NoSkill May 23 '23 at 14:01

1 Answers1

7

Screw it, I did a benchmark:

<?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 obviously does not iterate through the string but returns a pre-indexed value. No difference in speed.

Alasdair
  • 13,348
  • 18
  • 82
  • 138
  • For benchmarks like that it would be better to make higher difference between short and long string than 20%. Also variables names are missmatched. – ElChupacabra Nov 29 '18 at 09:18