Question: **Test One:**

```
class Entity { }

$entities = array();
echo "START: ". number_format(memory_get_usage()) . "\n";
for($i = 0; $i < 100000; ++$i)
{
    $entities[] = new Entity();
}
echo "BEFORE UNSET: ". number_format(memory_get_usage()) . "\n";
unset($entities);
echo "AFTER UNSET: ". number_format(memory_get_usage()) . "\n";

```

Output:

```
START: 631,664
BEFORE UNSET:44,404,904
AFTER UNSET: 8,954,568

```

---

**Test Two:**

```
class Entity { }

$entities = array();
echo "START: ". number_format(memory_get_usage()) . "\n";
for($i = 0; $i < 100000; ++$i)
{
    $entity = new Entity();
    $entities[] = &$entity;
}
echo "BEFORE UNSET: ". number_format(memory_get_usage()) . "\n";
unset($entities);
echo "AFTER UNSET: ". number_format(memory_get_usage()) . "\n";

```

Output:

```
START: 631,664
BEFORE UNSET: 10,480,480
AFTER UNSET: 631,752

```

After i had trouble with memory limit, I played around with it a bit...

So after that i wonder how does garbage collection really work:

1. Why does test **one** need more memory than test **two**?
2. Why does php keep memory after unsetting the array in test **one**?

thx dave

Answer: 
If there is no WHERE clause (like the query you posted) and you are selecting one million rows, there is a good chance that rather than the query taking 2-3 secs to execute it's in fact taking that time to send the data across the network. 

Can your application actually use a million database records at once? If you are showing that data to a user then you are likely going to be paging it, so change your query to select data in more manageable chunks.

```
SELECT id, value 
FROM foo
LIMIT $offset, $pgsize -- these two values will come from your application

```

If you really, really need all those rows at once, then I suggest you cache them.
Add an index to the fields used in the where clause.