Skip to content

Instantly share code, notes, and snippets.

@zualex
Created June 8, 2021 10:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zualex/98ae471611ee8459cc03401466272727 to your computer and use it in GitHub Desktop.
Save zualex/98ae471611ee8459cc03401466272727 to your computer and use it in GitHub Desktop.
Array vs SplFixedArray: memory usage
<?php
$sizes = [];
for ($exp = 0; $exp < 18; $exp++) {
$size = pow(2, $exp);
if ($size < 1000) {
continue;
}
$sizes[] = $size - ($size / 4);
$sizes[] = $size - ($size / 8);
$sizes[] = $size - ($size / 16);
$sizes[] = $size;
$sizes[] = $size + ($size / 16);
$sizes[] = $size + ($size / 8);
$sizes[] = $size + ($size / 4);
}
echo "size, memoryArray (KB), memorySpl (KB)" . PHP_EOL;
foreach ($sizes as $size) {
$startMemory = memory_get_usage();
$array = createOrdinaryArray($size);
$stopMemoryOrdinary = round((memory_get_usage() - $startMemory) / 1024, 2);
unset($array);
$startMemory = memory_get_usage();
$array = createSplArray($size);
$stopMemorySpl = round((memory_get_usage() - $startMemory) / 1024, 2);
unset($array);
echo "{$size}, {$stopMemoryOrdinary}, {$stopMemorySpl}" . PHP_EOL;
}
function createOrdinaryArray(int $size): array
{
$array = [];
for ($i = 0; $i < $size; $i++) {
$array[$i] = getValueArray($i);
}
return $array;
}
function createSplArray(int $size): SplFixedArray
{
$array = new SplFixedArray($size);
for ($i = 0; $i < $size; $i++) {
$array[$i] = getValueArray($i);
}
return $array;
}
function getValueArray($i)
{
return [
'id' => $i,
'price' => $i * 1000,
'name' => 'product #' . $i,
'description' => 'description product text 123 ' . $i,
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment