user1132363 user1132363 - 1 year ago 88
PHP Question

PHP - Are class constants any different from global constants in terms of memory?

This is a question about memory usage in PHP.

  • Is a class constant any different from a constant declared globally, in terms of memory use?

  • Does statically referring to a constant declared inside a class require more memory?

  • Does the class size (number & size of properties and methods) matter at all when statically referring to a constant inside it?

For clarity, class constant:

class Example {
const foo = 'bar';

global constant:

define('foo', 'bar');

Answer Source

I never thought of this, but is a good question.

Searching a little bit, I found that you can use memory_get_usage() to see the memory you are using before memory_get_usage executes.

So, try using it and you will see.

Do this:

echo memory_get_usage()."\n";
class Example {    
    const foo = 'bar';
echo memory_get_usage()."\n";
define('foo', 'bar');
echo memory_get_usage();

So there you will se how memory changes and that changes are the memory using.

I got this:

First echo: 349840
Second echo: 349840
Third echo: 349872

So, the difference is that the constant is pre-allocated, because if I comment class till the end, I get this memory 348664.

So, empty script: 348664, with class only: 349840, with global constant only: 348976.

Empty script: 0
Class: 1176
Global Constant: 312

So, there is a big difference.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download