Theia installation has been updated - September 10, 2011
« Feb. 2012
S M T W T F S
      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28        
Theia
In PHP: ($var += $data) is much faster than ($var = $var + $data)! « home
icon
posted on 13:58 - 18 June 2010 | posted by Lev
last modified on 14:06 - 18 June 2010 | last modified by Lev
A lot of the time I see people making the remark that in PHP this:
 
$var += $data;
 
... is the same as doing this:
 
$var = $var + $data;
 
Now, while that may be true in terms of overall accomplished effect, the reality is that the first method is a LOT faster, and the second method should be avoided whenever possible if performance is important.
 
To put this to the test, I created a simple script, with code like this:
 
for ($i = 1; $i <= 10000; $i++)
    {
    $var["$i"] = ".";
    }
foreach ($var as $v)
    {
    $d .= $v;
    }
 
I then added a microsecond timer and executed the script. Then I compared it to a script like this:
 
for ($i = 1; $i <= 10000; $i++)
    {
    $var["$i"] = ".";
    }
foreach ($var as $v)
    {
    $d = $d . $v;
    }
 
Needless to say I was a bit surprised with the results - the first method generates in about half as much time as the latter. To make sure this wasn't just a page-load fluke, I created another script which I used to invoke this test script 100 times to get an average from all the times the page was loaded - which is much more reliable than just testing it once or twice since so many factors contribute to effecting the page's generation time (how much is going on in the server at the moment and so forth).
 
Out of 100 page loads, the average generation time for the first method landed around 0.0206670427, whereas the average generation time for the second method clocked in at around 0.0393915224.
 
Fortunately for me, I always write code using the first method, but if you are someone who writes things the other way and do so in situations where lots of data is being handled, you might notice a bit of a performance increase by switching to the first method. Oh, and on a side note, the memory usage remains the same and is not effected by either of the methods.
 
So it seems as though reassigning a value to a variable is slower in PHP than merely adding additional data onto the variable. While by no means groundbreaking, it is at least good to know since there does seem to be a constant difference between the two approaches.
tags
post reply
Talasan
quote
posted by: guest 66.68.127.113 · date: 0:00 - 01 July 2010
Oh, really? I'm going to have to go through my code and check it out myself! Awesome find.
Bookmark item @
bookmarkbookmarkbookmarkbookmarkbookmark