PHP Speed: Count vs Empty
Lately there's been some talk about whether PHP or Ruby is
faster. The current data
on the web seems to say
Ruby is between 20% to 40% faster than PHP.
The only problem is the code being used is fundamentally different. The test is to implement the mergesort algorithm in the code (ie: not use the built-in sort functions).
In the original, Hongli Lai
used the following code to test if the arrays were empty in PHP:
while ( count($a) > 0 && count($b) > 0 )
(he used count twice more in the merge
function). Meanwhile he used this code in Ruby:
while !a.empty? && !b.empty?
Ruby's !a.empty? is equivalent to PHP's
!empty($a), and PHP's count($a) > 0
is equivalent to Ruby's a.length > 0.
I wasn't able to rerun the whole test, nor was I really
interested in it. I just wanted to compare the two
versions of the PHP code. As I suspected, using
empty proved to be about 50% faster.
The Procedure
I modified the code slightly to print the time it took to execute the mergesort 3,000 times. I tried to make this as unobtrusive as possible, so I think the result stands.
I used the version with count
and the version with !empty.
I fed these into PHP's CLI:
php -f count.php
The machine is a 2.4GHz Xeon with 1GB of RAM running RedHat Enterprise Linux 5 and PHP 5.2.3.
The Data
Here's the raw data for 10 trials of each. Times are in seconds.
Trial Empty Count 1 7.2021 14.1815 2 7.0843 14.3138 3 7.1855 14.2838 4 7.1291 14.2599 5 7.1194 14.9426 6 7.1097 14.9999 7 7.1415 14.6053 8 7.0952 14.1978 9 7.0631 14.3090 10 7.0529 14.2386 Avg 7.1183 14.4332 StDev 0.0486 0.3071 Var 0.0024 0.0943
The Results
I didn't really need to, but I did a t-test assuming unequal variance and α = 0.01 and the t-value was somewhere around 150.
So, confirming what we already knew, empty is
faster than count. But I also feel this invalidates
the previous tests.
I'm not concluding that PHP is faster than Ruby. (If the other tests are accurate, they're about the same.) I'm concluding that the methods of the previous tests were flawed.