Why is it that when the number of loops is increased, the execution is faster than when the number of loops is small?

42 Views Asked by At

Why is this code is faster the executiont time:

$start_foreach = microtime(true);
$counter = 1;
foreach (range(1, 1000) as $number) {
    $counter++;
}
$end_foreach = microtime(true);
$time_foreach = ($end_foreach - $start_foreach);
echo "\nExecution time of foreach-loop is $time_foreach second\n";

rather than:

$start_foreach = microtime(true);
$counter = 1;
foreach (range(1, 10) as $number) {
    $counter++;
}
$end_foreach = microtime(true);
$time_foreach = ($end_foreach - $start_foreach);
echo "\nExecution time of foreach-loop is $time_foreach second\n";

just why? I've been looping it many times but still give same result

Please someone explain it to me why is it so?

1

There are 1 best solutions below