Getting size in memory of an object in PHP?

In PHP, you can determine the memory size of an object by using the memory_get_usage() function before and after object creation. This approach measures the difference in memory consumption to estimate the object's size.

Basic Memory Measurement

The most straightforward method involves capturing memory usage before and after object instantiation −

<?php
class MyBigClass {
    var $allocatedSize;
    var $allMyOtherStuff;
    var $data = array();
}

function AllocateMyBigClass() {
    $before = memory_get_usage();
    $ret = new MyBigClass;
    $after = memory_get_usage();
    $ret->allocatedSize = ($after - $before);
    return $ret;
}

// Create object and display memory usage
$obj = AllocateMyBigClass();
echo "Object memory size: " . $obj->allocatedSize . " bytes
"; echo "Current memory usage: " . memory_get_usage() . " bytes"; ?>
Object memory size: 440 bytes
Current memory usage: 2097720 bytes

Memory Measurement with Real Memory

For more accurate results, use the real_usage parameter to get actual memory allocated by the system −

<?php
class DataClass {
    public $name;
    public $values = array();
    
    public function __construct($name) {
        $this->name = $name;
        for ($i = 0; $i < 100; $i++) {
            $this->values[] = rand(1, 1000);
        }
    }
}

function measureObjectSize($className, ...$args) {
    $before = memory_get_usage(true);
    $obj = new $className(...$args);
    $after = memory_get_usage(true);
    return array(
        'object' => $obj,
        'size' => ($after - $before)
    );
}

$result = measureObjectSize('DataClass', 'TestObject');
echo "Object size (real memory): " . $result['size'] . " bytes
"; echo "Object name: " . $result['object']->name; ?>
Object size (real memory): 0 bytes
Object name: TestObject

Key Points

Accuracy Limitations: Memory measurement in PHP can be affected by garbage collection, internal optimizations, and memory alignment. Small objects might show zero or negative differences.

Real vs Emulated: Use memory_get_usage(true) for actual system memory allocation, or memory_get_usage(false) for PHP's internal memory tracking.

Conclusion

While memory_get_usage() provides a basic way to estimate object memory consumption, results may vary due to PHP's memory management. This method is useful for profiling and optimization but should not be relied upon for precise memory calculations.

Updated on: 2026-03-15T08:46:09+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements