2013-07-18 2 views
1

Я замечал какое-то странное поведение, экспериментируя с бенчмаркингом SplFixedArrays. Возьмите этот небольшой фрагмент кода, например ...PHP, память и итерация

<?php 
$splFixedArray = new \SplFixedArray(100000); 
echo number_format(memory_get_usage()) . PHP_EOL; 
$variable = 'Truffaut single-origin coffee wayfarers, church-key asymmetrical 90\'s trust fund hashtag before they sold out thundercats photo booth. Godard sustainable roof party keffiyeh, Odd Future chillwave mlkshk kogi VHS leggings hoodie art party next level dreamcatcher yr. Blog american apparel aesthetic tattooed farm-to-table, stumptown viral whatever mixtape raw denim Williamsburg skateboard flexitarian actually tofu. Echo Park lomo disrupt PBR, jean shorts irony fingerstache blog kale chips. Street art iPhone PBR fingerstache Bushwick Cosby sweater. McSweeney\'s mumblecore semiotics, twee quinoa tofu +1 fingerstache pop-up. Echo Park bitters disrupt irony. Truffaut single-origin coffee wayfarers, church-key asymmetrical 90\'s trust fund hashtag before they sold out thundercats photo booth. Godard sustainable roof party keffiyeh, Odd Future chillwave mlkshk kogi VHS leggings hoodie art party next level dreamcatcher yr. Blog american apparel aesthetic tattooed farm-to-table, stumptown viral whatever mixtape raw denim Williamsburg skateboard flexitarian actually tofu. Echo Park lomo disrupt PBR, jean shorts irony fingerstache blog kale chips. Street art iPhone PBR fingerstache Bushwick Cosby sweater.'; 
var_dump($variable); 
for($i = 0; $i < 100000; $i++) 
{ 
    $splFixedArray[ $i ] = $variable; 
} 
echo number_format(memory_get_usage()); 

который выводит ...

1,032,080 
string(1209) "Truffaut single-origin coffee wayfarers, church-key asymmetrical 90's trust fund hashtag before they sold out thundercats photo booth. Godard sustainable roof party keffiyeh, Odd Future chillwave mlkshk kogi VHS leggings hoodie art party next level dreamcatcher yr. Blog american apparel aesthetic tattooed farm-to-table, stumptown viral whatever mixtape raw denim Williamsburg skateboard flexitarian actually tofu. Echo Park lomo disrupt PBR, jean shorts irony fingerstache blog kale chips. Street art iPhone PB"... 
1,032,384 

Теперь давайте добавим простое случайное число на конце в то время как в течение цикла ...

<?php 
$splFixedArray = new \SplFixedArray(100000); 
echo number_format(memory_get_usage()) . PHP_EOL; 
$variable = 'Truffaut single-origin coffee wayfarers, church-key asymmetrical 90\'s trust fund hashtag before they sold out thundercats photo booth. Godard sustainable roof party keffiyeh, Odd Future chillwave mlkshk kogi VHS leggings hoodie art party next level dreamcatcher yr. Blog american apparel aesthetic tattooed farm-to-table, stumptown viral whatever mixtape raw denim Williamsburg skateboard flexitarian actually tofu. Echo Park lomo disrupt PBR, jean shorts irony fingerstache blog kale chips. Street art iPhone PBR fingerstache Bushwick Cosby sweater. McSweeney\'s mumblecore semiotics, twee quinoa tofu +1 fingerstache pop-up. Echo Park bitters disrupt irony. Truffaut single-origin coffee wayfarers, church-key asymmetrical 90\'s trust fund hashtag before they sold out thundercats photo booth. Godard sustainable roof party keffiyeh, Odd Future chillwave mlkshk kogi VHS leggings hoodie art party next level dreamcatcher yr. Blog american apparel aesthetic tattooed farm-to-table, stumptown viral whatever mixtape raw denim Williamsburg skateboard flexitarian actually tofu. Echo Park lomo disrupt PBR, jean shorts irony fingerstache blog kale chips. Street art iPhone PBR fingerstache Bushwick Cosby sweater.'; 
var_dump($variable); 
for($i = 0; $i < 100000; $i++) 
{ 
    $splFixedArray[ $i ] = $variable . rand(); 
} 
echo number_format(memory_get_usage()); 

Какие результаты в этом ...

1,034,320 
string(1209) "Truffaut single-origin coffee wayfarers, church-key asymmetrical 90's trust fund hashtag before they sold out thundercats photo booth. Godard sustainable roof party keffiyeh, Odd Future chillwave mlkshk kogi VHS leggings hoodie art party next level dreamcatcher yr. Blog american apparel aesthetic tattooed farm-to-table, stumptown viral whatever mixtape raw denim Williamsburg skateboard flexitarian actually tofu. Echo Park lomo disrupt PBR, jean shorts irony fingerstache blog kale chips. Street art iPhone PB"... 
129,834,272 

То, что мне интересно, - это то, почему вызовы функций приводят к накопленной памяти. Нормально ли, что память не будет освобождена после итерации?

+2

Это чисто догадка, поэтому я оставляю это как комментарий: постоянное использование памяти в вашем первом примере, вероятно, связано с тем, что каждый элемент в вашем массиве ссылается на одну и ту же строку. Однако во втором примере, поскольку для каждого элемента массива строка различна, ей необходимо создать 100000 новых строк. – xbonez

ответ

3

Ожидается такое поведение.

В первом случае вы сохраняете одно и то же значение несколько раз, которое может быть реализовано как один экземпляр значения и пакет ссылок на него с семантикой copy-on-write для случаев, когда значение при заданном индексе массива.

Во втором случае вы храните много разных значений, которые нельзя обрабатывать одинаково; память должна быть выделена для полного содержимого каждого значения, что приводит к различию, которое вы видите в потреблении памяти между этими двумя случаями.

+1

Я уверен, что это так. Чтобы убедиться, что это так, можно было использовать 'xdebug_debug_val ('variable')' для отображения количества ссылок: http://php.net/manual/en/features.gc.refcounting-basics.php – jsalonen

+0

Yup, это то, чего я ожидал, но я хотел быть уверенным. – wlvrn

+0

Строка, длина которой составляет 1210 байт ... если она хранит копии, которые будут 121 000 000, только для значений в массиве в первом примере, поэтому нет способа сохранить их отдельно – Orangepill

Смежные вопросы