Reputation: 844
I am a PHP programmer. I always prefer to use x += 1;
instead of x = x + 1;
.
But still I don't understand why people say execution of x += 1;
is faster than x = x + 1;
.
(editor's note: This question didn't originally specify PHP, hence the comments and answers talking about C++ compilers.)
Upvotes: 1
Views: 1196
Reputation: 247
http://3v4l.org/GjPvL/vld#tabs will show you the answer.
$x += 1;
is interpreted as ASSIGN_ADD
$x = $x + 1;
has a separate add and assign operation and uses a temporary variable.
The less opcode, the faster it will run(in most cases).
Note that if you enable opcache with code optimization, $x = $x + 1;
will be optimized to use ASSIGN_ADD.
Upvotes: 4
Reputation: 2440
Decent compilers will pick up that
x = x +1
x += 1
x++
to be the same and in the end compile the same code, thus providing no difference.
Upvotes: 1
Reputation: 1496
+=
is what is called syntactic sugar. This is a convenience for developers. The two statements should have identical results in terms of logic and performance.
Upvotes: 1