Created
June 8, 2021 10:19
-
-
Save zualex/98ae471611ee8459cc03401466272727 to your computer and use it in GitHub Desktop.
Array vs SplFixedArray: memory usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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
https://docs.google.com/spreadsheets/d/1CvYtz40_HWFU_1ZMbzQQM5hykwD7hXPz8joTC8tCKgQ/edit#gid=646971508