PHP 陣列底層是有序雜湊表,每個元素約佔 48-72 位元組(64 位元系統)。一個含 100 萬個 double 的 C 陣列約 8 MB,但在 PHP 中可能高達 100 MB+(約 12-15 倍開銷)。長時間運行的 CLI 程式或高併發 Web 請求極易觸發 memory_limit。
將同質數值陣列序列化為二進位字串,讀取時再解包。字串在 PHP 內部為連續記憶體,開銷極低(約 1 位元組/字元 + 少量結構開銷)。
$total = 100_000;
$binary = '';
// 寫入:pack('d', float) 將 double 打包為 8 位元組二進位
for ($i = 0; $i < $total; $i++) {
$binary .= pack('d', $i + 0.1);
}
// 記憶體佔用對比
echo "陣列預估: " . ($total * 72 / 1024 / 1024) . " MB\n";
echo "字串實際: " . (strlen($binary) / 1024 / 1024) . " MB\n";
// 輸出約:陣列 7.2 MB vs 字串 0.76 MB(節省 90%+)
// 讀取:unpack('@offset/d', $binary) 從指定位移解包
for ($i = 0; $i < $total; $i++) {
$val = unpack('@' . ($i * 8) . '/d', $binary);
// $val[1] 即為第 i 個 double
// 處理業務邏輯...
}
class BinaryDoubleArray implements ArrayAccess, Countable, Iterator {
private string $buffer = '';
private int $count = 0;
private int $offset = 0; // 迭代器位置
public function append(float $value): void {
$this->buffer .= pack('d', $value);
$this->count++;
}
public function get(int $index): float {
if ($index < 0 || $index >= $this->count) throw new OutOfBoundsException();
return unpack('@' . ($index * 8) . '/d', $this->buffer)[1];
}
public function set(int $index, float $value): void {
if ($index < 0 || $index >= $this->count) throw new OutOfBoundsException();
$this->buffer = substr_replace($this->buffer, pack('d', $value), $index * 8, 8);
}
// 實作 ArrayAccess, Countable, Iterator 介面...
public function offsetExists(mixed $offset): bool { return $offset >= 0 && $offset < $this->count; }
public function offsetGet(mixed $offset): mixed { return $this->get($offset); }
public function offsetSet(mixed $offset, mixed $value): void { $this->set($offset, $value); }
public function offsetUnset(mixed $offset): void { throw new BadMethodCallException('不支援刪除'); }
public function count(): int { return $this->count; }
public function current(): mixed { return $this->get($this->offset); }
public function next(): void { $this->offset++; }
public function key(): mixed { return $this->offset; }
public function valid(): bool { return $this->offset < $this->count; }
public function rewind(): void { $this->offset = 0; }
}
// 使用
$arr = new BinaryDoubleArray();
for ($i=0; $i<100000; $i++) $arr->append($i * 0.1);
echo $arr[50000]; // 5000.0
foreach ($arr as $v) { /* 迭代 */ }
| 場景 | 是否適合 | 說明 |
|---|---|---|
| 大量同質數值(float/int) | ✅ 極佳 | 記憶體降 90%+,CPU 增 <10% |
| 異質資料/關聯陣列 | ❌ 不適合 | 需序列化整個結構,用 igbinary/msgpack |
| 頻繁隨機讀寫 | ⚠️ 可接受 | unpack/substr_replace 有函數呼叫開銷 |
| 需 JSON 序列化 | ⚠️ 需轉換 | 先轉陣列再 json_encode,或自訂序列化 |