Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP class objects and memory usage

Tags:

php

memory

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?

I'm wondering if it would be good for memory usage and performance to move some of the less-used methods to other places.

like image 664
Henk de Slager Avatar asked May 08 '11 14:05

Henk de Slager


2 Answers

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.

like image 61
Michael Berkowski Avatar answered Sep 28 '22 08:09

Michael Berkowski


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.

like image 43
Mark Baker Avatar answered Sep 28 '22 07:09

Mark Baker