Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the efficiency of strlen() in PHP?

Tags:

php

strlen

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.

like image 207
Alasdair Avatar asked Mar 02 '13 06:03

Alasdair


People also ask

What is strlen () used for in PHP?

The strlen() function returns the length of a string.

What is the time complexity of strlen?

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.

Does strlen count whitespace?

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.

Is strlen thread safe?

The strlen() function is thread-safe.


1 Answers

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.

like image 116
Alasdair Avatar answered Sep 19 '22 16:09

Alasdair