Home >Backend Development >PHP Tutorial >The difference between looping first and then judging and judging first and then looping.

The difference between looping first and then judging and judging first and then looping.

WBOY
WBOYOriginal
2016-07-06 13:53:392491browse

The difference between looping first and then judging and judging first and then looping.

The question for today’s interview. Tell me the advantages and disadvantages of the two writing methods

Reply content:

The difference between looping first and then judging and judging first and then looping.

The question for today’s interview. Tell me the advantages and disadvantages of the two writing methods

This is a guess question from the main exam, it is actually meaningless. The first paragraph is definitely good, the time is nf() 1, while the second paragraph is obviously nf() n.

Why is it a guessing question? In fact, few people write code in the first way, but

<code>$fName = 'doSomething';
if ($value) $fName = 'doOther';
for($i=0; $i < n; $i ++) $fName($i);</code>

The differences that come to mind are:

  1. The advantage of method one over method two is that you don’t need to make a judgment every time it loops, which improves efficiency

  2. When the judgment result may change, method two can make changes at any time, while method one cannot switch the operation method at any time

  3. Personally, I think the second method code looks better...


Actually, it just depends on what you need...the applicable situations are all different

This is probably the picture description

You can write a paragraph and see which one takes less time

The time complexity of the algorithms written in the 1.2 ways is the same, n.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn