I am writing a function that loops through different options. I was wondering whether it is more efficient having two loops or a condition within a loop.
Here's a very basic example. Lets assume I need to populate an array of Years and Quarters:
Example using two loops
$years = $quarters= [];
for($x = 1; $x <= 12; $x++) $months[] = $x;
for($x = 1; $x <= 4; $x++) $quarters[] = $x;
Example with if condition:
$years = $quarters= [];
for($x = 1; $x <= 12; $x++) {
$months[] = $x;
if($x <= 4) $quarters[] = $x;
}
In the second example the code needs to process the if condition 12 times. What code would be more efficient.
For the purpose of this question ignore readability and maintenance and only consider performance.
Aucun commentaire:
Enregistrer un commentaire