Memory optimizations when creating cache file

The following changes help to reduce the memory peak usage by up to 60%, tested with PHP 5.5 and 5.6:

- unset all variables as soon as possible
- split loop into multiple parts and change their order to be able to unset unnecessary data between those parts
- replace foreach loops with for loops
- use SplFixedArray where possible
- do not save data in object properties, but in temporary files, to reduce memory peak while preparing cache data