-2

Which loop is better between for and while loop ?

I need to know it for performance optimization.

Thank's a lot.

ssavajols
  • 1
  • 2
  • You get the best performance if you unroll all your loops. – Ja͢ck Jul 02 '14 at 09:04
  • 1
    The difference over the code's entire lifetime, if any, would be less than the amount of time you spent writing a question about it. If your code's too slow, this ain't the reason. – cHao Jul 02 '14 at 09:04
  • For loops are executed faster from a benchmark I have done with an array of 300k, but you must take into account array indexes... – ka_lin Jul 02 '14 at 09:31

3 Answers3

2

Do not try to tune performance on such a low level, write good and clean code and choose the loop that fits your use case. There will be no significant performance difference between for and while anyways, but that does not change the philosophy: do not butcher your code to tune performance.

LionC
  • 3,106
  • 1
  • 22
  • 31
0

None is better. You shouldn't even think about such base constructions performance. If you use loops right way, all would be good enough.

Marcin Nabiałek
  • 109,655
  • 42
  • 258
  • 291
-1

Using :

array array_map ( callable $callback , array $array1 [, array $... ] )

is better from both.

<?php
function cube($n)
{
    return($n * $n * $n);
}

$a = array(1, 2, 3, 4, 5);
$b = array_map("cube", $a);
print_r($b);
?>

This makes $b have:

Array
(
    [0] => 1
    [1] => 8
    [2] => 27
    [3] => 64
    [4] => 125
)
Yunis Hawwash
  • 98
  • 2
  • 13
  • how does this answer the question? he asked about two different kinds of loops, iterating over an array wasnt even mentioned – LionC Jul 02 '14 at 09:17