PHP class objects and memory usage
If I have a lot of instances of a single class, does the size of the class itself (the lines of code, the number of methods) have any influence on the required memory?
开发者_Python百科I'm wondering if it would be good for memory usage and performance to move some of the less-used methods to other places.
The class definition would be read by the compiler only once at the time it is include()
ed. The number of methods and number of lines of code should not have any meaningfull effect on the amount of memory used if you instantiate lots of class instances. However, the number of member variables will of course affect memory usage.
Some people will hate this suggestion; but if you have methods/attributes in your class that aren't specific to the instance, make them static methods/attributes. The non-static class methods/attributes should only be those that are instance specific.
Generally speaking, this won't help memory usage much (making attributes static will help memory). The individual instance only holds non-static class attributes, and the class methods are only held in memory once, no matter how many instances. Static attributes are held at a global level (don't confuse with global workspace), so they are only held in memory once, no matter how many instances.
The memory usage of objects is on par with that of arrays. A class eats a teensy bit more bytes. But that's not measurable unless you create a few thousand objects at once (in which case your real problem is another one).
Behind the scenes you always have a dictionary for the class attributes, and the class definition has an associated dictionary for the existing methods. The latter exists in either case, and just adding another method will add just a few bytes. In fact it's as much as registering a global function in the main function dictionary would.
So no, avoiding methods in your class declaration won't save memory. And it's not sensible, because the objects itself won't use more memory because of that. The method list isn't associated to the object instances.
精彩评论