Memory optimization in PHP array

Viewed 33921

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 want, but in my tiny VPS with only 256 ram, it's not an option.

I've been searching in stack and google and found several "well, you are using PHP not because memory efficiency, ditch it and rewrite in c++" and honestly, that's ok and I recognize PHP loves memory.

But, when digging more inside PHP memory management, I did not find what memory consumes every data type. Or if casting to another type of data reduces mem consumption.

The only "optimization" technique i found was to unset variables and arrays, that's it.

Converting the code to c++ using some PHP parsers would solve the problem?

Thanks!

3 Answers

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.

Related