Home>Article>Backend Development> Do variables occupy memory in php?
One way to store data in php is the amount that i can change. This method is to open up a space inmemory that can store data., give this space a name, and the space at this time can be called a variable.This value can be changed during operation
The name of the current space is the variable name, and the data (eight data types) of the current space is called the variable value
Example:(Recommended learning:PHP video tutorial)
php version is 7.2
'; $start = memory_get_usage(); $a = Array(); for ($i=0; $i<1000; $i++) { $a[$i] = $i + $i; } $mid = memory_get_usage(); echo memory_get_usage() , '
'; for ($i=1000; $i<2000; $i++) { $a[$i] = $i + $i; } $end = memory_get_usage(); echo memory_get_usage() , '
'; echo 'argv:', ($mid - $start)/1000 ,'bytes' , '
'; echo 'argv:',($end - $mid)/1000 ,'bytes' , '
'; echo 'Memory:', ($mid - $start)/1024 ,'k' , '
'; echo 'Memory:',($end - $mid)/1024 ,'k' , '
'; 输出是: 389336 418056 442632 argv:28.72bytes argv:24.576bytes Memory:28.046875k Memory:24k
Return to the current allocation The amount of memory given to your PHP script, in bytes.
It is roughly understood that an integer array of 1000 elements takes up 28k of memory, and each element occupies an average of 28 bytes
The results returned by memory_get_usage() are not all occupied by the array, but also To include some structures allocated by PHP
, the array generated by the built-in function may be closer to the real space:
'; echo 'Memory:', ($mid - $start)/1024 ,'k' , '
'; $b = array_fill(0, 10000, 1); $end = memory_get_usage(); //10k elements array; echo 'argv:', ($end - $mid)/10000 ,'byte' , '
'; echo 'Memory:',($end - $mid)/1024 ,'k' , '
'; 得到: argv:54.5792byte argv:54.5784byte argv:39.736byte Memory:388.046875k argv:39.736byte Memory:388.046875k
It is roughly understood that an integer array of 10,000 elements takes up 388k of memory, From this result, it seems that one array element takes up about 39 bytes.
The above is the detailed content of Do variables occupy memory in php?. For more information, please follow other related articles on the PHP Chinese website!