Static var and functions: memory allocation in php

I have doubts about memory allocation with php 5.3 script. Imagine you have 2 static classes (MyData and Test), for example:

class MyData { private static $data = null; public static function getData() { if(self::$data == null) self::$data = array(1,2,3,4,5,); return self::$data; } } class Test { private static $test_data = null; public static function getTestData1() { if(self::$test_data==null) { self::$test_data = MyData::getData(); self::$test_data[] = 6; } return self::$test_data; } public static function getTestData2() { $test = MyData::getData(); $test[] = 6; return $test; } } 

And a simple test.php script:

 for($i = 0; $i < 200000; $i++) { echo "Pre-data1 Test:\n\t" . memory_get_usage(true) . "\n"; Test::getTestData1(); echo "Post-data1 Test:\n\t" . memory_get_usage(true) . "\n"; } for($i = 0; $i < 200000; $i++) { echo "Pre-data2 Test:\n\t" . memory_get_usage(true) . "\n"; Test::getTestData2(); echo "Post-data2 Test:\n\t" . memory_get_usage(true) . "\n"; } 

I could assume that a call to Test :: getTestData1 () would allocate memory for two static variables, while Test :: getTestData2 () would destroy $ test (a copy of the static variable) on the return function, so the second call is less "expensive memory".

But if I run test.php script, memory_get_usage will show the same values ​​for Test :: getTestData1 () and Test :: getTestData2 ()

Why?

+4
source share
1 answer

You are testing memory usage incorrectly. use memory_get_usage(false); to get the memory that the script is actually using. memory_get_usage(true); just returns the memory allocated by the system, and it will always be the same for small scripts.

0
source

Source: https://habr.com/ru/post/1487250/


All Articles