Skip to content

Instantly share code, notes, and snippets.

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/70bf9670ae88548ee6706724784d4e14 to your computer and use it in GitHub Desktop.
Save zualex/70bf9670ae88548ee6706724784d4e14 to your computer and use it in GitHub Desktop.
Array vs SplFixedArray: memory usage simple
<?php
$sizes = [];
for ($exp = 0; $exp < 20; $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] = null;
}
return $array;
}
function createSplArray(int $size): SplFixedArray
{
$array = new SplFixedArray($size);
for ($i = 0; $i < $size; $i++) {
$array[$i] = null;
}
return $array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment