Search code examples
phpoopmemory-managementphp-internals

How (if possible) to optimize memory in this PHP example


I am trying to understand how PHP handles memory consumption in these two examples.

Example: 1

   // foo.php
    class foo{
        public function __construct()
        {
          $a = new PDO(...);
          $b = new StdClass; 
          $c = new Reflection; 
          $d = new SessionHandler; 
        }

        public function w(){}
        public function x(){}
        public function y(){}
        public function z(){}
     }

Example: 2

 class bar{ 
     public function __construct(){}

     public function w(){
        return new PDO(...); 
     }

     public function x(){
        return new StdClass;
     }

     public function y(){
        return new Reflection; 
     }
     public function z(){
        return new SessionHandler; 
     }
  }

Now depending on the above two example, I would like to know if these two calls, occupy the same amount of memory, or in other terms which one would be executed fast.

$foo = new foo(); 

###VS

$bar = new bar();
$bar->w(); 

I understand that class foo instantiates 4 objects during its instance alone, while class bar has one instance when it calls the method w(). This seems like, foo would take more memory, but I believe also, php parses everything when it reads the class, even the methods that are not invoked, it seems there is no real difference.


Solution

  • I believe also, php parses everything when it reads the class, even the methods that are not invoked

    Your belief is at least uninformed.

    Parsing (first stage) is a different stage in the execution of a script, actually executing it is another (second) stage.

    PHP does not execute any code prior to execution (second stage), it only compiles (first stage) the textual form of your code to a more compact, binary representation called opcodes - similar to the opcodes understood by the electronics in any CPU.

    This is the reason PHP modules called opcode cachers exist - to cache the opcodes and skip the parsing (first stage) of the textual representation.

    The most efficient way to do it memory-wise is to instantiate your resources lazily:

    class Foo
    {
        private $x;
    
        public function __construct()
        {
            //keep the constructor as lightweight as possible, ALWAYS
        }
    
        public function getX() {
            if(!$this->x) {
                 $this->x = new X();
            }
            return $this->x;
        }
    }