Monday 26 October 2020

Strange PHP memory usage in array of strings

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


from Strange PHP memory usage in array of strings

No comments:

Post a Comment