class Operation
{
private $op;
public function __construct()
{
$this->op = [];
for ($i = 1; $i < 1000; $i++)
{
$this->op[] = rand(1,9999);
}
}
public function getOps()
{
return $this->op;
}
}
class TestTellDontAsk
{
public function doItBAD(Operation $op)
{
foreach($op->getOps() as $item)
{
echo $item.'; ';
}
}
public function doItGOOD(array $ops)
{
foreach($ops as $item)
{
echo $item.'; ';
}
}
}
$m = [
memory_get_peak_usage(true),
memory_get_peak_usage(false),
memory_get_peak_usage(true),
memory_get_peak_usage(false)
];
$op = new Operation();
switch(mt_rand(0,1))
{
case 0: (new TestTellDontAsk())->doItBAD($op); break;
case 1: (new TestTellDontAsk())->doItGOOD($op->getOps()); break;
}
echo '<hr>';
echo memory_get_peak_usage(true) - $m[0].'<br>';
echo memory_get_peak_usage(false) - $m[1].'<br>';
echo memory_get_peak_usage(true) - $m[2].'<br>';
echo memory_get_peak_usage(false) - $m[3].'<br>';
this demostrates the whole in BAD and GOOD usage.
The doItBAD()
is bad, because passing an object is an unnecessary knowledge for the function but MEMORY-GOOD, since it just passes a reference, not the whole array itself
The doItGOOD()
is good, because it only passes an array but MEMORY-BAD, since it just passes a all the data instead of a reference.
Now how to decide which one to use?