Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does integer value take 72 bytes of memory? [duplicate]

Tags:

php

memory

Possible Duplicate:
What is the overhead of using PHP int?

Can somebody explain me, 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
like image 704
zim32 Avatar asked Sep 09 '11 07:09

zim32


People also ask

How is integer stored in memory?

Integers are commonly stored using a word of memory, which is 4 bytes or 32 bits, so integers from 0 up to 4,294,967,295 (232 - 1) can be stored. Below are the integers 1 to 5 stored as four-byte values (each row represents one integer).

What happens when you try to assign a value larger than the maximum possible integer to an int?

An integer overflow occurs when you attempt to store inside an integer variable a value that is larger than the maximum value the variable can hold. The C standard defines this situation as undefined behavior (meaning that anything might happen).


1 Answers

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.

like image 79
Jon Avatar answered Sep 22 '22 17:09

Jon