1

It looks like in PHP it requires about 213 bytes to store one integer, is it true? Okay, please take a look on the next code:

$N = 10000;
echo memory_get_usage()."\n";
$v = array();
for($i = 0; $i < $N; $i++) {
    $v[] = $i;
}
echo memory_get_usage()."\n";
unset($v);
echo memory_get_usage()."\n";

Output is next:

641784
2773768
642056

So, the difference is 2773768 - 641784 = 2131984 byte, or 213 byte per integer. why so much? 4 bytes is more than enough.

1 Answer 1

3

4 bytes is only enough if you simply store an integer value somewhere in memory, without making any allowance for the fact that it is a variable which needs a datatype identification, flags to indicate if there are any other references to that variable, the name of that variable, etc. all of which require additional memory.

PHP stores the value in a zval* so there's all the additional bytes used to store the zval details in addition to the actual value.

Sign up to request clarification or add additional context in comments.

2 Comments

Note also that 4-bytes for an integer value is correct for 32-bit PHP, if you're using 64-bit then it's 8-bytes
Note also that you're creating an array, which also has a zval structure, and the hashmap associated with mapping that array to the values it contains also has a memory overhead

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.