i recently read in a recent linux format article something along the lines of:
...some people already optimise their code, by pre-incrementing variables as opposed to post-incrementing variables, for example..."
I have absolutely NO idea what this means but i'd really like to know. Can anyone explain/give examples? Thanks.
basically, you increment before the operation and assignment, rather than incrementing after the operation.
from php manual http://www.php.net/manual/en/language.expressions.php
The following example should help you understand pre- and post-increment and expressions in general a bit better: function double($i) { return $i2; } $b = $a = 5; / assign the value five into the variable $a and $b / $c = $a++; / post-increment, assign original value of $a (5) to $c / $e = $d = ++$b; / pre-increment, assign the incremented value of $b (6) to $d and $e */ / at this point, both $d and $e are equal to 6 / $f = double($d++); / assign twice the value of $d <emphasis>before</emphasis> the increment, 26 = 12 to $f / $g = double(++$e); / assign twice the value of $e <emphasis>after</emphasis> the increment, 27 = 14 to $g / $h = $g += 10; / first, $g is incremented by 10 and ends with the value of 24. the value of the assignment (24) is then assigned into $h, and $h ends with the value of 24 as well. /
The following example should help you understand pre- and post-increment and expressions in general a bit better:
function double($i) { return $i2; } $b = $a = 5; / assign the value five into the variable $a and $b / $c = $a++; / post-increment, assign original value of $a (5) to $c / $e = $d = ++$b; / pre-increment, assign the incremented value of $b (6) to $d and $e */
/ at this point, both $d and $e are equal to 6 /
$f = double($d++); / assign twice the value of $d <emphasis>before</emphasis> the increment, 26 = 12 to $f / $g = double(++$e); / assign twice the value of $e <emphasis>after</emphasis> the increment, 27 = 14 to $g / $h = $g += 10; / first, $g is incremented by 10 and ends with the value of 24. the value of the assignment (24) is then assigned into $h, and $h ends with the value of 24 as well. /
Does this mean that writing my for loops
<? for($i=0;$i<count($array_name);++$i) ?>
is quicker or is it about the orientation of my script rather than just the function used?
I dont think it applies to PHP.
In say, C, ++i; tends to allow the compiler to generate simpler code than i++; so they tell me.