Home > Software design >  Trait vs Inhertance - Class-Definition's memory impact? (in PHP)
Trait vs Inhertance - Class-Definition's memory impact? (in PHP)

Time:11-04

When using inheritance in PHP, I am pretty sure that; the sub-class is NOT taking any extra memory based on number of methods defined in it's parent-class.

But consider below:

<?php

trait MyTrait {
    private $myTraitVariable = NULL;

    public function myTraitMethod() {
        // A lot of logic here...
    }
}

class MyClass1 {
    use MyTrait;
}

class MyClass2 {
    use MyTrait;
}

class MyClass3 {
    use MyTrait;
}

$instance1 = new MyClass1();
$instance2 = new MyClass2();
$instance3 = new MyClass3();
// ...

$instance1->myTraitMethod();
// ...

Will using PHP's Trait-feature now cause myTraitMethod's logic to take 3 times the memory, compared to inheritance?
(Or any other difference there?)

CodePudding user response:

Instance's memory usage

The memory footprint of $instance1, $instance2 and $instance3 will be basically the same whether inheritance is used or traits are used in their respective class definitions. This is because they need to create instances of objects they define as well as objects that are inherited via parents or "inherited" via traits.

Class-definition's memory usage

However this is different than the memory footprint of MyClass1, MyClass2 and MyClass3 definitions themselves.

When a trait is used in a class it is used like a "mixin". A class does not extend the trait but the trait is injected into the class definition. This can confirmed by considering that static trait properties get a separate copy on each class that uses the trait rather than having the same value for all classes as with inheritance. There may be optimisations to be made but again, this is really besides the point.

In that sense the memory footprint of the definitions using traits is more than the memory footprint of the definitions of inheritance.

However the last point is moot. Memory for declarations is generally very low unless you have a ridiculously amount of huge class declarations but if you do then this by itself is a bit of an indication that you need to start looking into separating your project into smaller parts. What occupies most memory when running code are object instances and in this case it does not matter if you use traits or inheritance but rather it matters what data goes in the objects.

  • Related