Reputation: 23
Using package ramsey/uuid I tried generating large amount of 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"
<?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"
Just invoking uuid generation does not cause any memory increase
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? 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
Upvotes: 2
Views: 217
Reputation: 17415
Strings in PHP are immutable, which means they can't be changed. 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. In the second case, you have an array with 100k elements, each referencing the same string.
For further reference, take a look at www.phpinternalsbook.com.
Upvotes: 6