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

后端 未结 8 2216
星月不相逢
星月不相逢 2020-12-23 02:02

In my PHP script I need to create an array of >600k integers. Unfortunately my webservers memory_limit is set to 32M so when initializing the array the script a

8条回答
  •  清酒与你
    2020-12-23 02:56

    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.

提交回复
热议问题