Question

I have recursive function:

function find($index, &$itemsCounts, &$amountsSums, $deep)

and in this function I call it again:

find($index, &$itemsCounts, &$amountsSums, $deep+1)

the max deep was 182 and peak of allocated memory was 751MB... I do not understand what takes so much memory in that recursive call....

Can somebody explain it? Does anybody know how much memory takes storing one that call on stack? Thanks

EDIT: the function looks like:

private function findChod($index, &$itemsCounts, &$amountsSums, $deep){
    if($amountsSums['a'] > $this->upperLimit) return;
      $check_string = "";

      if($deep > $this->maxDeep) $this->maxDeep = $deep;

    foreach ($this->x[$index]['a'] as $key => $item) {
      $check_string = $check_string." ".$itemsCounts[$key];
    }

    if(isset($this->memo[$check_string]))
      return;

    $this->memo[$check_string] = 1;

     $a = "asda;"
     $b = "asda;"
     $c = "asda;"
     $d = "asda;"
     $e = "asda;"
     $f = "asda;"

    if() return;

    if(){
      if(){
        $this->compareWithBest($amountsSums, $itemsCounts, abs($fatsDifference)+abs($protsDifference)+abs($carbsDifference));
      }
    }

    unset($a);
    unset($b);
    unset($c);

    unset($d);
    unset($e);
    unset($f);

    foreach ($this->x[$index]['items'] as $key => $item) {
      $amountsSums['a'] +=  $item['a'] * $item['unit'];
      $amountsSums['b'] +=  $item['b'] * $item['unit'] ;
      $amountsSums['c'] +=  $item['c'] * $item['unit'];
      $amountsSums['d'] +=  $item['d'] * $item['unit'];
      $itemsCounts[$key]++;

      $this->find($index, $itemsCounts, $amountsSums, $deep+1);

      $amountsSums['a'] -=  $item['a'] * $item['unit'];
      $amountsSums['b'] -=  $item['b'] * $item['unit'];
      $amountsSums['c'] -=  $item['c'] * $item['unit'];
      $amountsSums['d'] -=  $item['d'] * $item['unit'];
      $itemsCounts[$key]--;
    }
  }

where memo has at peak 1 900 000 items... and I`m using php 5.5.3

EDIT2: I discovered that variable memo takes cca 307MB

EDIT3: I rewrite my algorithm so I did not need memory at all...

Was it helpful?

Solution

PHP's arrays are far away from classical arrays. It's a data structure which implements a linked list and a hash table. There's a lot of overhead which reflects obviously in memory consumption. I don't know no implementation detail about them, but the fact that it eats 300MB for only 1900000 * (10 byte indexes + 4 byte values) implies that you just cannot have large arrays in PHP.

I just recently learned that PHP offers indeed access to a classical array which consumes far less memory. PHP calls it SplFixedArray. But this won't help you, as you in deed need the functionality of a hash map.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top