- memory_get_peak_usage: documentation ( source)
- microtime: documentation ( source)
- array_merge: documentation ( source)
- gc_enable: documentation ( source)
- gc_disable: documentation ( source)
- range: documentation ( source)
<?php
// Benchmarking function with garbage collection disabled
function benchmark($callback, $iterations = 100)
{
gc_disable(); // Disable garbage collection for clearer memory tracking
$startTime = microtime(true);
$startMemory = memory_get_peak_usage();
for ($i = 0; $i < $iterations; $i++) {
$callback();
}
$endTime = microtime(true);
$endMemory = memory_get_peak_usage();
gc_enable(); // Re-enable garbage collection
return [
'time' => $endTime - $startTime,
'peak_memory' => $endMemory - $startMemory,
];
}
// Test data - larger arrays to better see memory impact
$baseArray = range(1, 1000);
$newData = range(1001, 2000);
// Method 1: Using array_merge in a loop
$mergeArray = $baseArray;
$mergeBenchmark = benchmark(function () use (&$mergeArray, $newData) {
$tempArray = $mergeArray; // Clone array for memory comparison
$mergeArray = array_merge($tempArray, $newData);
});
// Method 2: Using array unpacking in a loop
$unpackArray = $baseArray;
$unpackBenchmark = benchmark(function () use (&$unpackArray, $newData) {
$tempArray = $unpackArray; // Clone array for memory comparison
$unpackArray = [...$tempArray, ...$newData];
});
// Display results
echo "Array Merge:\n";
echo "Time: " . $mergeBenchmark['time'] . " seconds\n";
echo "Peak Memory: " . $mergeBenchmark['peak_memory'] . " bytes\n\n";
echo "Array Unpacking:\n";
echo "Time: " . $unpackBenchmark['time'] . " seconds\n";
echo "Peak Memory: " . $unpackBenchmark['peak_memory'] . " bytes\n";