I am currently creating a socket server in PHP and I would like to know which one would be faster to use throughout it. I've heard for loops are faster than while loops, but I don't know about do whiles.
Thanks
I am currently creating a socket server in PHP and I would like to know which one would be faster to use throughout it. I've heard for loops are faster than while loops, but I don't know about do whiles.
Thanks
Depending on the benchmark you use, do
loops have been shown to be marginally faster:
http://www.ebrueggeman.com/blog/php_benchmarking_loops
Test Avg Execution Time
for loop 23.44 ms
while loop 24.65 ms
do while loop 22.96 ms
In this benchmark, foreach
was shown to out-perform other loop types, and while
was found to out-perform for
. I bring this up because you will note that this contradicts the first test I cite.
Finally, this benchmark supports the findings of the first, that while
is marginally faster than for
.
The conclusion? No benchmark is capable of emulating your use case to the extent that you should base your decision on it, and this may be a micro-optimization that won't materially improve your program. Use the statement that fits the situation, then write tests to benchmark your own application using variations. It is pretty trivial to swap the while
and the for
-- try them both and see what you get. Then unlearn that lesson for your next project, because it will be unique and again deserve individual testing.
Documentation
If you're so concerned with speed of your code, profile it. Whatever you read about the specific code snippets' performance (in places like this, for example), might turn wrong in your specific case - because of some weird PHP interpreter quirk, or something.
There's a plenty of profiling tools available for PHP programmer - starting from a simple microtime, ending with complete profiler toolkits like XDebug. I suggest reading this topic for basic guidelines of profiling.
There is no difference per se as they're basically just different ways of writing loops, directly taken from C.
The only thing that can be impacting is the number of times a condition is evaluated but you can count it yourself.
So use what is the most concise and readable.
Use whatever fits your purpose. for loops and while loops are used to loop with the condition checked first. do-whiles guarantee that the code is run at least once.
Thus you can immediately narrow down your choices to either for/while or do-while based on this constraint. Trying to use an inappropriate construct would result in very ugly code which most likely be slower anyways.
Between for and while, I don't think there's any difference. Even if you were writing a scientific library, this would barely be noticeable (if at all). The general guideline is: for loops are designed for iterating through things and while loops are used as other general purpose looping.