How to Reduce PHP Array Memory Usage with String Packing
This article explains why PHP arrays consume far more memory than their C equivalents and demonstrates a technique that stores a double array in a string using pack/unpack, which can dramatically lower memory consumption at the cost of some performance.
Generally, PHP arrays use only about one‑tenth of the memory efficiency of C arrays; an array that occupies 100 MB in C may require around 1 GB in PHP.
This high memory consumption is especially problematic for backend servers written in PHP.
Because the issue stems from the language itself, conventional optimizations are difficult, but a string‑based solution can help.
$total = 100000;
$double = "";
for ($i = 0; $i < $total; $i++) {
$double .= pack("d", $i + 0.1);
}
for ($i = 0; $i < $total; $i++) {
unpack("@" . ($i * 8) . "/d", $double);
}The example stores a double array inside a string and later extracts each value with unpack.
While this approach reduces memory usage, it may affect performance, so it should be applied based on specific requirements.
For instance, if you have ten 10 MB arrays (about one million elements each), they would consume roughly 100 MB of memory, which can become insufficient under concurrent access.
By storing each array as a string and unpacking only when needed, you can alleviate memory pressure.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
21CTO
21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
