PHP to see a variable of memory instance code

Time:2021-3-5

example:

PHP version is 7.2

<?php
echo memory_get_usage() , '<br>';
$start = memory_get_usage();
$a = Array();
for ($i=0; $i<1000; $i++) {
$a[$i] = $i + $i;
}
$mid = memory_get_usage();
echo memory_get_usage() , '<br>';
for ($i=1000; $i<2000; $i++) {
$a[$i] = $i + $i;
}
$end = memory_get_usage();
echo memory_get_usage() , '<br>';
echo 'argv:', ($mid - $start)/1000 ,'bytes' , '<br>';
echo 'argv:',($end - $mid)/1000 ,'bytes' , '<br>';
echo 'Memory:', ($mid - $start)/1024 ,'k' , '<br>';
echo 'Memory:',($end - $mid)/1024 ,'k' , '<br>';
The output is:
389336
418056
442632
argv:28.72bytes
argv:24.576bytes
Memory:28.046875k
Memory:24k

Returns the amount of memory currently allocated to your PHP script in bytes.

About 1000 elements of the integer array need to take up 28K memory, each element takes up an average of 28 bytes

memory_ get_ The results returned by usage () are not all occupied by arrays, but also include some PHP

For some structures allocated by running itself, the array generated by the built-in function may be closer to the real space

<?php
$start = memory_get_usage();
$a = array_fill(0, 10000, 1);
$mid = memory_get_usage(); //10k elements array;
echo 'argv:', ($mid - $start )/10000,'byte' , '<br>';
echo 'Memory:', ($mid - $start)/1024 ,'k' , '<br>';
$b = array_fill(0, 10000, 1);
$end = memory_get_usage(); //10k elements array;
echo 'argv:', ($end - $mid)/10000 ,'byte' , '<br>';
echo 'Memory:',($end - $mid)/1024 ,'k' , '<br>';
The results are as follows
argv:54.5792byte
argv:54.5784byte

argv:39.736byte
Memory:388.046875k
argv:39.736byte
Memory:388.046875k

It is estimated that an integer array of 10000 elements takes up 388k of memory. From this result, it seems that an array element takes up about 39 bytes.

Content supplement

How to get the memory size of variable in PHP


$start_memory = memory_get_usage();
$foo = "Some variable";
echo memory_get_usage() - $start_memory;

This can get the size of all variable types

Strlen ($foo) this can get the byte size of the current string divided by 8, which is the bit size

So far, this article about PHP to view the memory occupied by a variable instance code is introduced here. For more related PHP how to view the memory occupied by a variable, please search previous articles of developer or continue to browse the following related articles. I hope you can support developer more in the future!