萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 陣列記憶體優化:用二進位字串替代大型陣列

問題背景

PHP 陣列底層是有序雜湊表,每個元素約佔 48-72 位元組(64 位元系統)。一個含 100 萬個 double 的 C 陣列約 8 MB,但在 PHP 中可能高達 100 MB+(約 12-15 倍開銷)。長時間運行的 CLI 程式或高併發 Web 請求極易觸發 memory_limit。

解決方案:pack()/unpack() 二進位字串

將同質數值陣列序列化為二進位字串,讀取時再解包。字串在 PHP 內部為連續記憶體,開銷極低(約 1 位元組/字元 + 少量結構開銷)。

實作範例:儲存 10 萬個 double

$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,或自訂序列化

替代方案

  • SplFixedArray:固定長度、類 C 陣列,記憶體約為標準陣列 1/3,支援隨機存取 O(1)。
  • igbinary/msgpack 擴展:高效二進位序列化,適合快取/儲存異質結構。
  • PHP 8.1+ Fiber/共享記憶體:跨進程共享大資料集。
copyright © 萬盛學電腦網 all rights reserved