开发者

PHP [OOP] : Memory allocation for Inheritance

开发者 https://www.devze.com 2022-12-14 02:48 出处:网络
Please see the code bellow: class A { public x = 5; public y = 6; public z = 7; } class B extends A { public m = 1;

Please see the code bellow:

class A {
    public x = 5;
    public y = 6;
    public z = 7;
}

class B extends A {
    public m = 1;
    public n = 2;
}

$a = new A();
$b = new B()
开发者_StackOverflow社区

From the above code let $a is allocating x amount of memory and $b is allocating y amount of memory;

Now my question is which one is correct from bellow?

x > y

x < y


These are my numbers:

Starting allocation 62480
Allocated memory for new A() 328
Allocated memory for new B() 496

Thus x < y

These two class definitions are equivalent

class B extends A {
    public $m = 1;
    public $n = 2;
}

class C {
    public $x = 5;
    public $y = 6;
    public $z = 7;
    public $m = 1;
    public $n = 2;
}

Meaning that were you to change the definition of B into that of C then the memory usage would be the exact same for using new B() or new C().

To run it yourself use this code (as an example)

$start = memory_get_usage();
echo "Starting allocation $start\n";
$a = new A();
$diff = memory_get_usage() - $start;
echo "Allocated memory for new A() $diff\n";
$b = new B();
$diff = memory_get_usage() - $start - $diff;
echo "Allocated memory for new B() $diff\n";


You can investigate this by using the memory_get_usage function.


It should be public $x, $y, $z.

And $b takes up more memory because it has an instance of A inside.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号