I am curious, if I create a class of many methods (functions as PHP still call them) which many of them are not used and I create an object, does it create memory for all methods even if most methods aren't being used? I'm doing PHP OOP coding.
views:
45answers:
2In general, creating a new instance of a class does not copy the methods - all instances of a class share a single copy of each methods , whether it's used or not. Depending on the language, the table linking method names to the actual (shared) method itself may or may not be shared, however - I'm not sure what PHP does here.
Now, take this with a grain of salt because this is from memory and I can't find my original sources, but if I remember correctly, memory is allocated by class.
Once you have a class that's loaded, it will have all methods loaded into memory, even if they are not being executed yet. Then if you have new instances of that class, PHP will reference the original class for methods. It will allocate it's own memory space for members, though. Note that there is a distinction between class and instance.
//this is a class (obviously)
class foo {
__construct(){
print "constructing foo\n";
}
public function bar(){
print "called bar\n";
}
}
//this is the first instantiation of that class,
//the class already has methods loaded in memory, ready to run.
//bar is never called, but it's still in memory, just waiting.
$my_foo = new foo();
//this is the second instance, everything is already loaded,
//if you call bar, there's no need to reallocate anything.
$your_foo = new foo();
$your_foo->bar();
The above will load the class foo which in turn loads the construct and bar methods (as well as others that are built in). Then when you instantiate it, it doesn't need to allocate space for methods, it just references the already loaded methods. So in my example, the bar()
method is already loaded and waiting, no need to reallocate space.
Of course this gets to be a bit tricky when talking about private methods/members as well as references to instances. Suffice it to say that if you're worried that much, then PHP may not be the language to be using.
Not sure if there's a way to dig into PHP code to see what memory is allocated as you would easily be able to with C, for instance. You would probably have to go that low-level in order to answer the question in your specific case.