Steven Vachon

Benchmark: PHP strlen vs. count (and sizeof)

0 comments

I was writing some code that generated a string from an array and came across a pretty rare situation where I could either get the length of that array or the length of the assembled string. Wondering which was faster and finding nothing on Google, I put this benchmark together.

For the sake of search engines, I included sizeof() in the title. There was no need to include it in the benchmark as it’s the same as count() and runs at the same speed.

Function Time Comparison
strlen() 0.237 seconds (8.85% faster)
count() 0.260 seconds

Here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<?php
 
$test_array = array(0,1,2,3,4,5);
$test_string = '/test/';
 
function getmicrotime()
{
	list($usec, $sec) = explode(' ',microtime());
	return ((float)$usec + (float)$sec);
}
 
$time_start = getmicrotime();
for ($i=0; $i<1000000; $i++)
{
	count($test_array);
}
echo 'count() :: '.number_format(getmicrotime()-$time_start,3).' seconds<br/>';
 
$time_start = getmicrotime();
for ($i=0; $i<1000000; $i++)
{
	strlen($test_string);
}
echo 'strlen() :: '.number_format(getmicrotime()-$time_start,3).' seconds<br/>';
 
?>


Comments

Top

Leave a Reply

Comments welcome! Name & email required; email always kept private. Please use basic markup. Wrap code with <code> tags.