Search code examples
phparraysarray-map

Why does memory overflow when using array_map for big array?


When I'm testing array_map() function. There is a very strange phenomenon.

Normal size array

$array = range(1, 100000);
echo memory_get_usage();
array_map(function($value) {}, $array);
echo memory_get_usage();

Result

8649024
8649024

It's obvious that the memory size is equal.

But for big array

$array = range(1, 10000000);
echo memory_get_usage();
array_map(function($value) {}, $array);
echo memory_get_usage();

Result

84319040

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 36 bytes) in G:\phpStudy\WWW\testSpeed.php on line 6

Why? I have search answer everywhere. But it seems that there are few people have this problem. If anyone can help me? Thank you!


Solution

  • array_map() applies call back function to each element in original array. so the function executes per each element in array and tries to allocate memory to result. when the limit of the memory usage(for executing function for each array element+ array elements) exceeds the memory allocated , this error occurs. In this example array map doesn`t have to do anything with memory exhaustion. It`s the range() function which throws error when it tries to allocate memory to the array which is trying to create