Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Which is faster - array_sum or a foreach?

I'm trying to work out which method would be faster (if either would be?). I've designed a test here: http://codepad.org/odyUN0xg

When I run that test my results are very inconsistent. Both vary wildly.

Is there a problem with the test?

otherwise, can anyone suggest which one would or wouldn't be faster??

Edit

Okay guys, thanks I've edited the codepad here: http://codepad.org/n1Xrt98J With all the comments and discussion i've decided to go with array sum. As soon as I used that microtime(true) thing it started to look alot faster (array_sum)

Cheers for the advice, oh and I've added a "for" loop so that results are more even, but as noted on the results there is little time saving if any over a foreach.

like image 487
Jason Avatar asked Dec 06 '25 04:12

Jason


1 Answers

The problem is that you took a very low limit, 1000. The overhead of the PHP interpreter is MUCH larger. I would take 100000000 or something like that.

However I think array_sum is faster since it's more specialized and probably implemented in fast C.

Oh, and as Michael McTiernan said you must change every instance of microtime() to microtime(true). http://php.net/manual/en/function.microtime.php

And finally, I wouldn't use codepad as testing environment since you have no control over it. You have no idea what happens and whether your process is paused or not.

like image 77
orlp Avatar answered Dec 08 '25 17:12

orlp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!