Need an array-like structure in PHP with minimal memory usage Need an array-like structure in PHP with minimal memory usage arrays arrays

Need an array-like structure in PHP with minimal memory usage


The most memory efficient you'll get is probably by storing everything in a string, packed in binary, and use manual indexing to it.

$storage = '';$storage .= pack('l', 42);// ...// get 10th entry$int = current(unpack('l', substr($storage, 9 * 4, 4)));

This can be feasible if the "array" initialisation can be done in one fell swoop and you're just reading from the structure. If you need a lot of appending to the string, this becomes extremely inefficient. Even this can be done using a resource handle though:

$storage = fopen('php://memory', 'r+');fwrite($storage, pack('l', 42));...

This is very efficient. You can then read this buffer back into a variable and use it as string, or you can continue to work with the resource and fseek.


A PHP Judy Array will use significantly less memory than a standard PHP array, and an SplFixedArray.

I quote "An array with 1 million entries using regular PHP array data structure takes 200MB. SplFixedArray uses around 90 megabytes. Judy uses 8 megs. Tradeoff is in performance, Judy takes about double the time of regular php array implementation."


You could use an object if possible. These often use less memory than array's.Also SplFixedArray is an good option.

But it really depends on the implementation that you need to do. If you need an function to return an array and are using PHP 5.5. You could use the generator yield to stream the array back.