简体   繁体   English

字符串数组中奇怪的 PHP 内存使用情况

[英]Strange PHP memory usage in array of strings

Using package ramsey/uuid I tried generating large amount of uuids v4.使用包ramsey/uuid我尝试生成大量 uuids v4。

<?php

require __DIR__ . '/vendor/autoload.php';
use Ramsey\Uuid\Uuid;

$initialMemoryUsage = memory_get_usage(true) / 1024 / 1024;
$test = [];

for ($i = 0; $i < 100000; $i++) {
    $test[] = Uuid::uuid4()->toString();
}

var_dump(sprintf('Memory used: %d MB', (memory_get_usage(true) / 1024 / 1024) - $initialMemoryUsage));

outputs: string(18) "Memory used: 10 MB"输出: string(18) "Memory used: 10 MB"

<?php

$initialMemoryUsage = memory_get_usage(true) / 1024 / 1024;
$test = [];

for ($i = 0; $i < 100000; $i++) {
    $test[] = '97c2ca84-bcfe-4618-b8a3-4d404eead37a';
}

var_dump(sprintf('Memory used: %d MB', (memory_get_usage(true) / 1024 / 1024) - $initialMemoryUsage));

outputs string(17) "Memory used: 4 MB"输出string(17) "Memory used: 4 MB"

Just invoking uuid generation does not cause any memory increase仅调用 uuid 生成不会导致任何内存增加

for ($i = 0; $i < 100000; $i++) {
    Uuid::uuid4()->toString();
}

How come that in both cases the result is array of string(36) with 100000 elements but amount of used memory differs?为什么在这两种情况下结果都是具有 100000 个元素的 string(36) 数组但使用的内存量不同? Any ideas?有任何想法吗?

php -v

PHP 7.3.2-3+ubuntu16.04.1+deb.sury.org+1 (cli) (built: Feb  8 2019 15:43:26) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.2, Copyright (c) 1998-2018 Zend Technologies

Strings in PHP are immutable, which means they can't be changed. PHP 中的字符串是不可变的,这意味着它们不能被更改。 This also implies that they can easily be shared.这也意味着它们可以轻松共享。 In the first case, you have an array with 100k elements, each referencing a different string.在第一种情况下,您有一个包含 100k 个元素的数组,每个元素引用一个不同的字符串。 In the second case, you have an array with 100k elements, each referencing the same string.在第二种情况下,您有一个包含 100k 个元素的数组,每个元素都引用相同的字符串。

For further reference, take a look at www.phpinternalsbook.com .如需进一步参考,请查看www.phpinternalsbook.com

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM