PHP - Pre Vs Post Incrementing / Decrementing

PHP - Pre vs Post Incrementing/Decrementing

Looking to shave some time off of page loads, but your logic is as slim as it can get?  Well I can help. Here is an easy fix that can speed up an application through a few tweaks to your PHP code

Depending on your application, you may have many incrementing/decrementing variables strewn about your site.  Let's review the two, and key points as far as performance.

Post Incrementing/Decrementing

Whenever you use the ++ or -- operators after a variable name, this is post incrementing or decrementing, respectively.  What the PHP parser does, is makes a copy of the variable to return, and then adds or subtracts 1 from the value.  This takes more time and resources, since it has to do more work. This should only be used when you need to immediately return the value before it is modified.

Pre Incrementing/Decrementing

Using the ++ or -- operators before a variable is pre incrementing or decrementing. This is much faster than it's counterpat, because it doesn't need to do anything other than directly modify the variable, and then return it.  You should use this whenever you can!  It can be as much as three times faster than the post method.

Now you may be thinking: "How much can that help?"

Well consider the following:


$x = 0

while ($x < $some_var) {

//Do something




Now if $some_var is two or three, probably not going to save much. But if it were 25? or 50? It's not entirely irrational to think that a while loops such as this one could go into the hundreds.  with each loop, the performance gain becomes more and more valuable.  Plus, it's just good form to is the "pre" method whenever possible.


Add a comment

0 answers +0 votes
Post comment Cancel