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.
The strlen() function returns the length of a string.
The time complexity of standard strlen is O(n). Since all trailing characters are '\0', we can use binary search. By comparing middle two elements with '\0', we can decide whether we need to recur for left half or right half. IF one of them is \0, then we found the first occurrence.
The strlen() function in C returns an integer with the length of the string excluding the NULL character. The strlen() function counts the alphabets, whitespaces, special symbols, and numbers until it encounters the NULL character in the string.
The strlen() function is thread-safe.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With