、while、do-whileループのプロファイルを、単純なもので作成しました。
while ($var < 1000000) {
++$var;
}
do {
++$var;
} while ($var < 1000000);
for ($var = 0; $var < 1000000; ++$var) {
//do nothing
}
ループの前後のmicrotime()を比較します。
do-whileループは、かなりの量で最速のループです。do-whileは、実際にはwhileよりもほぼ半分高速です。私はそれらが異なる目的のためであることを知っています(ループが実行される前に条件をチェックし、do-whileが少なくとも1回実行されます)。
私は、一般的なコンセンサスは、whileループが眉をひそめていることを知っています。
私の質問はなぜですか?PHPアプリケーションで使用されているforループの数を考えると、使用すべきではありません。ループが実行される前に条件をチェックするifステートメントを使用しても、パフォーマンスは大幅に向上します。
私の現在受け入れられている答えは、コードの読みやすさが疑わしいということです。
10年編集: 10年前、就職の面接でこの質問をされました。私は、whileループが眉をひそめているという誤った認識でインタビューに入りました。これは、上司からの指示に従って、コードでwhileループが許可されていなかった以前の仕事から学びました。
The interview had gone well with management, then I was handed over to the lead programmer, he asked me what the fastest loop in PHP was, which I got incorrect and I did not get the job, this is why I asked the question on SO.
10 years of experience has taught me a lot.
- while loops are fine (its ludicrous to think I was taught otherwise)
- Micro-optimizations are truly evil (profile code, focus on bottle necks)
- in 10 years, I have never re-written a loop for speed. I have however rewritten the logic inside the loop which was always the true bottleneck.
- There is a lot of strongly held but largely incorrect opinions in the programming field. Stay the course, read up, experiment and question, be open to learning from better programmers and dont be afraid to be wrong.