Memory optimization in PHP array

前端 未结 3 1429
青春惊慌失措
青春惊慌失措 2020-12-04 10:35

I\'m working with a large array which is a height map, 1024x1024 and of course, i\'m stuck with the memory limit. In my test machine i can increase the mem limit to 1gb if i

3条回答
  •  攒了一身酷
    2020-12-04 11:10

    A little bit late to the party, but if you have a multidimensional array you can save a lot of RAM when you store the complete array as json.

    $array = [];
    
    $data = [];
    $data["a"] = "hello";
    $data["b"] = "world";
    

    To store this array just use:

    $array[] = json_encode($data);
    

    instead of

    $array[] = $data;
    

    If you want to get the arrry back, just use something like:

    $myData = json_decode($array[0], true);
    

    I had a big array with 275.000 sets and saved about 36% RAM consumption.

    EDIT: I found a more better way, when you zip the json string:

    $array[] = gzencode(json_encode($data));
    

    and unzip it when you need it:

    $myData = json_decode(gzdecode($array[0], true));
    

    This saved me nearly 75% of RAM peak usage.

提交回复
热议问题