Reputation: 23198
Two pieces of code that do the same thing:
class Dog
{
public $name;
public $breed;
}
$hachi = new Dog;
$hachi->name = "Hachi";
$hachi->breed = "Shiba";
vs
$hachi->name = "Hachi";
$hachi->breed = "Shiba";
In this context (using the class as a struct), both code will achieve the same thing. Is there any benefit for using the long-winded version besides readability/style? Are there performance issues or anything else that should prevent me from short-cutting it?
Upvotes: 1
Views: 75
Reputation: 26413
Actually yes, even aside from the obvious maintainability issue there is another benefit. With pre-declared properties PHP only needs a single hashtable per class that maps the property names to offsets in memory-efficient C arrays used for each object. Using dynamic properties PHP needs a hashtable per object.
So as soon as you've got more than one object of that type, you're saving memory.
How much? Let's pretend you've got a lot of dogs.
"long-winded" version:
class Dog
{
public $name;
public $breed;
}
while (@$i++ < 1000000) {
$hachi = new Dog();
$hachi->name = "Hachi";
$hachi->breed = "Shiba";
$dogs[] = $hachi;
}
echo memory_get_usage(true); //188747776
"short-cut" version:
while (@$i++ < 1000000) {
$hachi = new stdClass();
$hachi->name = "Hachi";
$hachi->breed = "Shiba";
$dogs[] = $hachi;
}
echo memory_get_usage(true); //524292096
For a difference of 524292096 - 188747776 = 335,544,320 bytes.
For a lengthier explanation see: Why objects (usually) use less memory than arrays in PHP
Upvotes: 3
Reputation: 9782
Classes are intended to help organize data, and that definitely adds overhead.
If you are trying to write code that does a good job representing the data you will be working with, you will have to accept some performance penalties.
The second approach will create code that is virtually impossible to maintain.
PHP gives us a very simple way to define an object programmatically, and this is called a class. A class is a wrapper that defines and encapsulates the object along with all of its methods and properties. You can think of a class as a programmatic representation of an object, and it is the interface that PHP has given you, the developer, to interact with and modify the object. Moreover, a class may be re-used infinitely if need be, making it very powerful and codebase friendly. You do not have to redefine things every time you want to use an object - a properly coded class is setup to do all of the work for you.
From: http://www.htmlgoodies.com/beyond/php/object-orientated-programming-in-php-class-1-principles.html
Upvotes: 1
Reputation: 59
if both codes work then go for the short one, adding it into a class will not make it any faster or efficient, its good practice and can help if you are adding allot of code to generate it. But performance wise the second one will work better
Upvotes: -1