Reputation: 89663
PHP manual states that:
Adding 3 to the current value of $a can be written '$a += 3'. This means exactly "take the value of $a, add 3 to it, and assign it back into $a". In addition to being shorter and clearer, this also results in faster execution.
I used to think that $a += 3
is merely syntax sugar for $a = $a + 3
and thus they should be equal in all respects.
Why does $a += 3
result in faster execution compared to $a = $a + 3
?
Upvotes: 7
Views: 175
Reputation: 6513
PHP is an interpreter, so, in order to have a good performance for good code, it must restrict itself to do not do "valid" complex opimizations (as compilers can do, because they have time for that).
Since the time of asembler, it is better to have =+
than its equivalent sum, just becouse it uses less resources.
In the case of PHP, it tokenizes =+
to T_PLUS_EQUAL
, also best executed by PHP executable, and in the other hand, the sum, well, it is tokenized (and executed) just like a sum.
Following the "dumps" from both token_get_all()
<?php echo '<pre>';
print_r(array_map(function($t){if(is_array($t)) $t[0]=token_name($t[0]); return $t;},
token_get_all('<?php $a=$a+3 ?>')));
print_r(array_map(function($t){if(is_array($t)) $t[0]=token_name($t[0]); return $t;},
token_get_all('<?php $a+=3 ?>')));
// results in:
?>
Array
(
[0] => Array
(
[0] => T_OPEN_TAG
[1] => 1
)
[1] => Array
(
[0] => T_VARIABLE
[1] => $a
[2] => 1
)
[2] => =
[3] => Array
(
[0] => T_VARIABLE
[1] => $a
[2] => 1
)
[4] => +
[5] => Array
(
[0] => T_LNUMBER
[1] => 3
[2] => 1
)
[6] => Array
(
[0] => T_WHITESPACE
[1] =>
[2] => 1
)
[7] => Array
(
[0] => T_CLOSE_TAG
[1] => ?>
[2] => 1
)
)
Array
(
[0] => Array
(
[0] => T_OPEN_TAG
[1] => 1
)
[1] => Array
(
[0] => T_VARIABLE
[1] => $a
[2] => 1
)
[2] => Array
(
[0] => T_PLUS_EQUAL /// <= see here!!!!!
[1] => +=
[2] => 1
)
[3] => Array
(
[0] => T_LNUMBER
[1] => 3
[2] => 1
)
[4] => Array
(
[0] => T_WHITESPACE
[1] =>
[2] => 1
)
[5] => Array
(
[0] => T_CLOSE_TAG
[1] => ?>
[2] => 1
)
)
Upvotes: 3
Reputation: 12985
$a = $a + 3
might use a temporary variable in the PHP VM.
While $a += 3
might execute directly.
PS: I emphasize the might. Very not sure...
It might be similar to C++
's: ++i
vs. i++
:)
Upvotes: 0
Reputation: 212442
$a = $a + 3
adds 3 to $a in a temporary memory space, then assigns the result to $a; while $a += 3
adds 3 directly to $a; so the difference is a few bytes of memory for temporary storage, plus an assignment
Upvotes: 4