Home » Php » php – stdClass vs array. Which is recommended?

php – stdClass vs array. Which is recommended?

Posted by: admin July 12, 2020 Leave a comment

Questions:

Where is recommended to use one of them? I want to store data from articles listed from db.

It’s a simple question:

echo $Datastore->name; //I like it works with foreach

//vs

echo $Datastore['name'];

Which is the best? Is there any difference between stdClass and array speed of getting elements?

How to&Answers:

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.