Memory leak when executing Doctrine query in loop

后端 未结 6 1769
梦毁少年i
梦毁少年i 2020-12-31 07:32

I\'m having trouble in locating the cause for a memory leak in my script. I have a simple repository method which increments a \'count\' column in my entity by X amount:

6条回答
  •  青春惊慌失措
    2020-12-31 07:38

    You're wasting memory for each iteration. A much better way would be to prepare the query once and swap arguments many times. For example:

    class MyEntity extends EntityRepository{
        private $updateQuery = NULL;
    
        public function incrementCount($id, $ammount)
        {
            if ( $this->updateQuery == NULL ){
                $this->updateQuery = $this->createQueryBuilder('e')
                    ->update('MyEntity', 'e')
                    ->set('e.count', 'e.count + :amount')
                    ->where('e.id = :id')
                    ->getQuery();
            }
    
            $this->updateQuery->setParameter('id', $id)
                    ->setParameter('amount', $amount);
                    ->execute();
        }
    }
    

    As you mentioned, you can employ batch processing here, but try this out first and see how well (if at all) performs...

提交回复
热议问题