Current Location: Home> Latest Articles> How to Accurately Measure Object Memory Usage in PHP

How to Accurately Measure Object Memory Usage in PHP

M66 2025-06-24

Getting the Size of an Object in Memory in PHP

In PHP development, understanding the memory size occupied by an object is important for performance optimization and memory management. We can use PHP's built-in memory_get_usage() function to measure the memory allocated before and after object creation.

Example Code

class MyBigClass {
    var $allocatedSize;
    var $allMyOtherStuff;
}
<p>function AllocateMyBigClass() {<br>
$before = memory_get_usage();<br>
$ret = new MyBigClass;<br>
$after = memory_get_usage();<br>
$ret->allocatedSize = ($after - $before);<br>
return $ret;<br>
}

Code Explanation

In the AllocateMyBigClass() function, the current memory usage $before is recorded before creating an instance of MyBigClass. After the object is created, the memory usage $after is recorded again. The difference between the two values is the memory size occupied by the object, which is then assigned to the object's allocatedSize property.

Notes

This method provides a relative measure of memory usage which might be influenced by PHP’s internal memory management mechanisms and should be used as a reference. For precise analysis, it’s recommended to use this approach alongside other profiling tools and methods.