Skip to content

Instantly share code, notes, and snippets.

@augustohp
Created May 30, 2014 02:30
Show Gist options
  • Save augustohp/c2044d70b336b64a0bac to your computer and use it in GitHub Desktop.
Save augustohp/c2044d70b336b64a0bac to your computer and use it in GitHub Desktop.
Usar array estoura a memória do PHP.
<?php
function printResults()
{
$startOfRequest = $_SERVER['REQUEST_TIME'];
$memoryUsed = formatBytes(memory_get_usage());
$memoryPeak = formatBytes(memory_get_peak_usage());
echo <<<EOT
Memory usage: $memoryUsed
Memory peak: $memoryPeak
EOT;
}
function createRandonString()
{
return md5(mt_rand());
}
function populateIteator($iterator, $length=999999)
{
$result = $iterator;
for($i=0; $i<$length; $i++)
$result[$i] = createRandonString();
return $result;
}
function doSomethingWithIterator($iterator)
{
// whatever
}
// http://stackoverflow.com/questions/2510434/format-bytes-to-kilobytes-megabytes-gigabytes
function formatBytes($bytes, $precision = 2)
{
$kilobyte = 1024;
$megabyte = $kilobyte * 1024;
$gigabyte = $megabyte * 1024;
$terabyte = $gigabyte * 1024;
if (($bytes >= 0) && ($bytes < $kilobyte)) {
return $bytes . ' B';
} elseif (($bytes >= $kilobyte) && ($bytes < $megabyte)) {
return round($bytes / $kilobyte, $precision) . ' KB';
} elseif (($bytes >= $megabyte) && ($bytes < $gigabyte)) {
return round($bytes / $megabyte, $precision) . ' MB';
} elseif (($bytes >= $gigabyte) && ($bytes < $terabyte)) {
return round($bytes / $gigabyte, $precision) . ' GB';
} elseif ($bytes >= $terabyte) {
return round($bytes / $terabyte, $precision) . ' TB';
} else {
return $bytes . ' B';
}
}
$currentScript = array_shift($argv);
$runProgram = array_shift($argv);
$arrayLength = array_shift($argv) ?: 999999;
switch($runProgram) {
case 'array':
$array = populateIteator(array(), $arrayLength);
doSomethingWithIterator($array);
doSomethingWithIterator($array);
printResults();
break;
case 'object':
$array = populateIteator(new ArrayObject($arrayLength), $arrayLength);
doSomethingWithIterator($array);
doSomethingWithIterator($array);
printResults();
break;
default:
echo "Usage: $currentScript <array|object> [length=999999]";
echo PHP_EOL;
break;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment