Skip to content

Instantly share code, notes, and snippets.

@janmartenjongerius
Created July 31, 2016 15:41
Show Gist options
  • Save janmartenjongerius/bf2d70cad59957d54a6936a5a9b62da0 to your computer and use it in GitHub Desktop.
Save janmartenjongerius/bf2d70cad59957d54a6936a5a9b62da0 to your computer and use it in GitHub Desktop.
Proof of concept: generators versus array builders
#!/usr/bin/env php
<?php
/**
* Fibonacci number creator.
*
* @param int $grandparent
* @param int $parent
* @return int
*/
function f(int $grandparent, int $parent): int
{
return intval($parent + $grandparent);
}
/**
* A classical fibonacci range builder.
*
* @param int $length
* @return int[]
*/
function builder(int $length): array
{
$grandparent = 0;
$parent = 1;
$range = [$grandparent, $parent];
for ($i = 0; $i <= $length; $i++) {
$child = f($grandparent, $parent);
$grandparent = $parent;
$parent = $child;
$range[] = $child;
}
return $range;
}
/**
* Generator for fibonacci numbers.
*
* @param int $length
*
* @yields int
*/
function generator(int $length)
{
$grandparent = 0;
$parent = 1;
for ($i = 0; $i <= $length; $i++) {
yield $child = f($grandparent, $parent);
$grandparent = $parent;
$parent = $child;
}
}
$maxNumIterations = 999999;
for ($numIterations = 0; $numIterations < $maxNumIterations; $numIterations++) {
gc_collect_cycles();
$builderUsage = 0;
foreach (builder($numIterations) as $fibonacciNumber) {
$currentUsage = memory_get_usage(false);
if ($currentUsage > $builderUsage) {
$builderUsage = $currentUsage;
}
}
gc_collect_cycles();
$generatorUsage = 0;
foreach (generator($numIterations) as $fibonacciNumber) {
$currentUsage = memory_get_usage(false);
if ($currentUsage > $generatorUsage) {
$generatorUsage = $currentUsage;
}
}
echo sprintf(
"#%d\tBuilder: %.2f kb\tGenerator: %.2f kb\t%d",
$numIterations,
$builderUsage / 1024,
$generatorUsage / 1024,
$fibonacciNumber
) . PHP_EOL;
if ($builderUsage > $generatorUsage) {
echo sprintf(
'Found difference at iteration #%d and fibonacci number %d',
$numIterations,
$fibonacciNumber
) . PHP_EOL;
break;
}
}
@janmartenjongerius
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment