mattalxndr
mattalxndr

Reputation: 9418

Is there a way to free the memory allotted to a Symfony 2 form object?

I am trying to optimize an import operation that uses Symfony 2 forms to validate data during the import process, a bit like this much simplified example:

/// For each imported row
foreach ($importedData as $row) {

    $user = new User;
    $userType = new UserType;

    // !! The 250 KB of memory allotted in this line is never released again !!
    $form = $symfonyFormFactory->create($userType, $user);

    // This line allots a bunch of memory as well,
    // but it's released when the EM is flushed at the end
    $form->bind($row);

    if (!$form->isValid()) {
        // Error handling
    }

    $entityManager->persist($user);
    $entityManager->flush();
}

Each one of those loops, memory usage is increasing by around 250 KB, which is crippling for large imports.

I have discovered that the memory leak is coming from the $form = $symfonyFormFactory->create(new UserType, $user); line.

EDIT: The bulk of the memory was being used by the entity manager, not the form component (see accepted answer). But the loop is still taking 55 KB each loop, which is better than 250 KB but could be better. Just not today.

Upvotes: 1

Views: 912

Answers (2)

Vadim Ashikhman
Vadim Ashikhman

Reputation: 10136

Try to disable SQL logging to reduce memory usage

$entityManager->getConnection()->getConfiguration()->setSQLLogger(null)

Also i just found similar question here

Upvotes: 2

karlisba
karlisba

Reputation: 3

Are you sure you don't want to release entity object? First of all, don't flush data in every iteration. Lets say persist 50 objects - I don't know how big is your import data - and flush them together, then clear the object by simply calling $entityManager->clear();

Upvotes: 0

Related Questions