Why does integer value take 72 bytes of memory? [duplicate]
Possible Duplicate:
What is the overhead of using PHP int?
Can somebody explain m开发者_开发技巧e, why creation of an integer in PHP, costs 72 bytes?
var_dump(memory_get_usage()); //49248 bytes
$a = 255;
var_dump(memory_get_usage()); // 49320 bytes
I don't have extensive knowledge of PHP internals, but the concept is that when you create a variable with an integer value, PHP internally allocates a structure (such structures are usually called variants) that is capable of holding any type of value in the language (which includes object types, functions, etc). This is bound to require more than a lowly 4 bytes.
With that out of the way, the question that remains is why 72 (and not for example 42)? For an answer to this we 'd need to examine not only the C source (to see exactly what is allocated and what its memory footprint is) but also the implementation of memory_get_usage
(to see how exactly it counts memory usage).
Update: I feel I need to stress the "how it counts memory usage" part more.
It is entirely possible that the allocation of a new variable causes PHP's memory allocator to reserve a block of memory from the C heap substantially larger than what it needs to satisfy the variable allocation request (it can also decide to keep this memory future use even after you e.g. unset
the variable).
If memory_get_usage
wants to count the whole memory block as "used", then you could even see a simple integer variable cause usage to go up by, say, 1K (if things were as simple as I have described so far, an additional integer allocation would then not cause memory usage to increase).
My point here is that you cannot call the memory usage results unexpected until you can fully define what the expected results are. And this is not possible without looking at the source for memory_get_usage
.
It is probably due to the way PHP allocates memory. The files are not compiled down into binary so they are not pushing four bytes onto the stack or being allocated on the heap, but rather allocating memory on a virtual stack.
Setting any variable will use up a particular amount of memory, so that you can do the following without any errors:
$a = 100;
//...then later in the code
$a = 100000;
//or
$b = "hello";
//...then later in the code
$b = "hello world this is a long string to show how long a string can be.";
It may also be because PHP is a preprocessing language, not a program that converts your code to binary then the binary code is run.
精彩评论