PhpSpreadsheet uses a Cells collection class to manage cell data for each worksheet. This collection implements an intelligent caching system that minimizes memory usage while maintaining performance.
// When accessing a cell:// 1. Check if it's the current active cell (in memory)if ($cellCoordinate === $this->currentCoordinate) { return $this->currentCell;}// 2. Store current cell to cache if dirty$this->storeCurrentCell();// 3. Load requested cell from cache$cell = $this->cache->get($this->cachePrefix . $cellCoordinate);// 4. Set as active cell$this->currentCell = $cell;
This architecture ensures only one cell is fully loaded in memory at a time, dramatically reducing memory usage.
When no cache is configured, PhpSpreadsheet uses an in-memory cache implementation:
public static function getCache(): CacheInterface{ if (!self::$cache) { self::$cache = self::useSimpleCacheVersion3() ? new Memory\SimpleCache3() : new Memory\SimpleCache1(); } return self::$cache;}
The implementation is automatically selected based on your PSR-16 version.Source: Settings.php:95-102
Strategy 2: Separate Cache Instances for Large Operations
Use different cache backends for different operations:
use PhpOffice\PhpSpreadsheet\Settings;class CacheStrategy{ public static function setForReading(): void { // Fast cache for reading $pool = new ApcuCachePool(); $cache = new SimpleCacheBridge($pool); Settings::setCache($cache); } public static function setForWriting(): void { // Redis for writing (persistence) $client = new \Redis(); $client->connect('127.0.0.1', 6379); $pool = new RedisCachePool($client); $cache = new SimpleCacheBridge($pool); Settings::setCache($cache); }}// Reading operationCacheStrategy::setForReading();$spreadsheet = IOFactory::load('input.xlsx');$data = $spreadsheet->getActiveSheet()->toArray();// Writing operationCacheStrategy::setForWriting();$newSpreadsheet = new Spreadsheet();// ... populate data$writer = new Xlsx($newSpreadsheet);$writer->save('output.xlsx');
Cause: Excessive serialization/deserialization overheadSolution: Consider using APCu which keeps objects in memory, or increase batch size for operations