Question

If I run the following PHP program on my computer

echo memory_get_usage();
echo "|";
echo memory_get_usage();
echo "|";
echo memory_get_usage();

I get the output

635048|635080|635080

From this, it appears the initial call to memory_get_usage is retaining 32KB of memory. I tried this without the echo statements

echo memory_get_usage();
echo memory_get_usage();
echo memory_get_usage();

and got a similar result

634504634536634536
//broken out 634504, 634536, 634536

While removing the echo statements reduced the overall memory usage of the script, there's still the 32KB being retained after the initial call to memory_get_usage. Why is this?

I've tried this on multiple computers, and while the actual numbers differ, the gap remains the same.

If I look at (what I think is) the source of this function

//File: php-5.3.19/ext/standard/var.c
PHP_FUNCTION(memory_get_usage) {
    zend_bool real_usage = 0;

    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &real_usage) == FAILURE) {
        RETURN_FALSE;
    }

    RETURN_LONG(zend_memory_usage(real_usage TSRMLS_CC));
}

I don't see anything in there that necessarily says "retain this variable in memory". However, I haven't written C seriously in years and I've never professionally hacked on the PHP source and my ability to trace execution is nill.

So, my question is, what's retaining that 32KB of memory, and where does that happen in the PHP source code and/or how can I trace that from the memory_get_usage entry point.

Was it helpful?

Solution

This is probably the result of having to create output. Perhaps there's some output buffering involved?

At the command prompt:

[charles@lobotomy /tmp]$ php --version
PHP 5.4.9 (cli) (built: Nov 22 2012 12:59:04)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.4.0, Copyright (c) 1998-2012 Zend Technologies
    with Xdebug v2.2.0rc1, Copyright (c) 2002-2012, by Derick Rethans
[charles@lobotomy /tmp]$ cat test.php
<?php
#echo '|';
echo memory_get_usage();
echo '|';
echo memory_get_usage();
echo '|';
echo memory_get_usage();
echo '|';

[charles@lobotomy /tmp]$ php test.php
227024|227056|227056|

When test.php is modified to echo before the first measurement, we get

[charles@lobotomy /tmp]$ cat test.php
<?php
echo '|';
echo memory_get_usage();
echo '|';
echo memory_get_usage();
echo '|';
echo memory_get_usage();
echo '|';

[charles@lobotomy /tmp]$ php test.php
|227192|227192|227192|
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top