PHP 在从变量定义变量并将对象实例转换为另一个变量时是否占用 RAM? [英] Does PHP take RAM when defining variable from variable and taking instance of object to another variable?
问题描述
如果我有这个代码
<?php
$array = array();
for ($i=1;$i<100000;$i++){
$array[$i] = md5(rand(0,9999999999999999));
}
$array2 = $array;
$array
大约需要 0.5MB RAM,比方说.PHP proccess 使用 $array2 = $array;
需要大约 1.0MB RAM 吗?在这种情况下
$array
takes about 0.5MB RAM, let's say. Does PHP proccess take about 1.0MB RAM with $array2 = $array;
? and in this case
<?php
class rand{
public $array;
function rand(){
$this->array = array();
for ($i=1;$i<100000;$i++){
$this->array[$i] = md5(rand(0,9999999999999999));
}
}
}
$class = new rand();
$class2 = $class;
$class
大约需要 0.5MB RAM,比方说.使用 $class2 = $class
时 PHP 进程是否需要 1.0MB?
$class
takes about 0.5MB RAM, let's say
. Does PHP proccess take 1.0MB with $class2 = $class
?
是一样的吗?
测试:
推荐答案
这是参考部分的 PHP 手册警告的:引擎足够智能.设置 $array2 = $array;
不会 导致重复存储,因为 PHP 认识到它们仍然相同.但是,在此之后尝试 $array[2] = 'something;'
.PHP 检测到差异,只有 then 会复制这些值.
This is what the PHP manual in the reference section warns about: the Engine is smart enough. Setting the $array2 = $array;
does not cause duplicate storage, as PHP recognizes they are still both the same. However, try a $array[2] = 'something;'
after that. PHP detects the difference, and only then will copy the values.
<?php
$array = array();
for ($i=1;$i<100000;$i++){
$array[$i] = md5(rand(0,9999999999999999));
}
echo memory_get_usage().PHP_EOL;
$array2 = $array;
echo memory_get_usage().PHP_EOL;
$array['foo'] = 'bar';
echo memory_get_usage().PHP_EOL;
//17252052
//17252156
//23776652
类在默认情况下是引用,只有一个 clone $object
会在 PHP >= 5 中产生 2 个对象.
Classes are references by default, and only a clone $object
would result in 2 objects in PHP >= 5.
这篇关于PHP 在从变量定义变量并将对象实例转换为另一个变量时是否占用 RAM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!