Home >Backend Development >PHP Tutorial >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
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:
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
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
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.