PHP Objects VS Arrays -- Performance Comparison While Iterating

stdClass vs array. Which is recommended?

There is a similar question What is better stdClass or (object) array to store related data? with this answer

Based on small test (http://phpfiddle.org/lite/code/cz0-hyf) I can say
that using "new stdClass()" is about 3 times slowlier than other
options.

It is strange, but casting an array is done very efficiently compared
to stdClass.

But this test meters only execution time. It does not meter memory.

P.S. I used phpFiddle only to share code. Test were done at my local
PC.

In answer to another similar question you can see this conclusion:

  1. For arrays, PHP 5.5 is faster than PHP 5.4, for object it is pretty much the same
  2. Class is slower than Arrays thanks to the optimization of PHP 5.5 and arrays.
  3. stdClass is evil.
  4. Class still uses less memory than Arrays. (about 30-40% less!!).
  5. SplFixedArray is similar to use a Class but it uses more memory.

Is there any performance benefit of using objects in php?

If using php5 an object is slightly faster than an array but in most cases the difference is negligible

Here is a link to a performance test:
http://aggregation.novaak.net/?q=node/227

PHP Variable vs Array vs Object

I would consider it unnecessary overhead. Doing what you are talking about in an object-oriented way only means that inside your class you will have done nothing more than create a bunch of variables, just as you specified in your first example.

The array is the best way to go in my opinion. You are only using one variable, and you can also integrate it into your Class. So, instead of $tpl->title, you may have $tpl->text['title'].

Performance of FOR vs FOREACH in PHP

My personal opinion is to use what makes sense in the context. Personally I almost never use for for array traversal. I use it for other types of iteration, but foreach is just too easy... The time difference is going to be minimal in most cases.

The big thing to watch for is:

for ($i = 0; $i < count($array); $i++) {

That's an expensive loop, since it calls count on every single iteration. So long as you're not doing that, I don't think it really matters...

As for the reference making a difference, PHP uses copy-on-write, so if you don't write to the array, there will be relatively little overhead while looping. However, if you start modifying the array within the array, that's where you'll start seeing differences between them (since one will need to copy the entire array, and the reference can just modify inline)...

As for the iterators, foreach is equivalent to:

$it->rewind();
while ($it->valid()) {
$key = $it->key(); // If using the $key => $value syntax
$value = $it->current();

// Contents of loop in here

$it->next();
}

As far as there being faster ways to iterate, it really depends on the problem. But I really need to ask, why? I understand wanting to make things more efficient, but I think you're wasting your time for a micro-optimization. Remember, Premature Optimization Is The Root Of All Evil...

Edit: Based upon the comment, I decided to do a quick benchmark run...

$a = array();
for ($i = 0; $i < 10000; $i++) {
$a[] = $i;
}

$start = microtime(true);
foreach ($a as $k => $v) {
$a[$k] = $v + 1;
}
echo "Completed in ", microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => &$v) {
$v = $v + 1;
}
echo "Completed in ", microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => $v) {}
echo "Completed in ", microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => &$v) {}
echo "Completed in ", microtime(true) - $start, " Seconds\n";

And the results:

Completed in 0.0073502063751221 Seconds
Completed in 0.0019769668579102 Seconds
Completed in 0.0011849403381348 Seconds
Completed in 0.00111985206604 Seconds

So if you're modifying the array in the loop, it's several times faster to use references...

And the overhead for just the reference is actually less than copying the array (this is on 5.3.2)... So it appears (on 5.3.2 at least) as if references are significantly faster...

EDIT: Using PHP 8.0 I got the following:

Completed in 0.0005030632019043 Seconds
Completed in 0.00066304206848145 Seconds
Completed in 0.00016379356384277 Seconds
Completed in 0.00056815147399902 Seconds

Repeated this test numerous times and ranking results were consistent.

Why is an extended ArrayObject faster than the original ArrayObject?

It is because your function using the extended array object is not setting $z['aaa'] 2000 times but your function using ArrayObject is.

if i add a version of the extended array object function which does set $z['aaa'] the result is more consistant:

profiling(function()
{
global $times;
for ($i=0; $i<$times; $i++) {
$z = new MyArray();
for ($j=0; $j<$times; $j++) {
$z['bbb'] = 'bbb';
$z['ccc'] = $z['aaa'].$z['bbb'];
}
}
}, 'use extends arrayobject (no aaa)');

/* added MyArray function with $z['aaa'] = 'aaa' added to the loop */
profiling(function()
{
global $times;
for ($i=0; $i<$times; $i++) {
$z = new MyArray();
for ($j=0; $j<$times; $j++) {
$z['aaa'] = 'aaa';
$z['bbb'] = 'bbb';
$z['ccc'] = $z['aaa'].$z['bbb'];
}
}
}, 'use extends arrayobject (with aaa)');

output is as follows:

use array: 1.3838648796082
use object: 1.9023339748383
use arrayobject: 2.0339980125427
use extends arrayobject (no aaa): 1.6399688720703
use extends arrayobject (with aaa): 2.040415763855
phpversion 5.4.4-14+deb7u7

notice that the function using ArrayObject and the function using the extended ArrayObject with $z['aaa'] in the loop have much closer times.

Value objects vs associative arrays in PHP

Under the surface, the two approaches are equivalent. However, you get most of the standard OO benefits when using a class: encapsulation, inheritance, etc.

Also, look at the following examples:

$arr['naem'] = 'John';

is perfectly valid and could be a difficult bug to find.

On the other hand,

$class->setNaem('John');

will never work.

PHP | Updating array items through function while iterating - Big performance issue

speed up php only solution
Apart from the suggested use of a database to organize your stuff, if you still want it the hard way ;) you can avoid iterating (let php do it internaly) over the whole array by using one of the php functions below:

array_map
— Applies the callback to the elements of the given arrays

and

array_walk
— Apply a user function to every member of an array

I see in your code, you have the 'use' clause, so I presume you are PHP > 5.3. In that case, you can do the following:

$yourdata = array_map(
function($row) use ($user)
{
/*$user->doStuff();*/
return $row;
}, $yourdata
);

Furthermore, a lot of overhead is the display rendering part. If you have a lot of things to display, for example using a simple echo, it's faster to do:

$result = "";
$result .= $something;
$result .= $somethingelse;
echo $result;

than

echo $something;
echo $somethingelse;

enhance solution to use database
But besides that, it will surely be beneficial if you use the database. The most obvious thing is to store your data in some db tables and use some sql-ish solution to query it. It will speed your script up for sure.

speed up the db+php solution
Next, you can get a major performance boost by doing most of your calculations (business logic) inside the database engine in form of stored procedures.

For example if you'd go with mysql, you could create a cursor and iterate over your table rows in a loop. On every row you do some stuff, while ofcourse having direct access to all the tables/columns of your scheme (and possibly other stored procedures/functions). If you are doing a lot of math-ish calculations it's a great solution, but ofcourse IMHO it's usually less convenient (more sophisticated) to write your stuff in SQL rather than PHP ;)



Related Topics



Leave a reply



Submit