【问题标题】:How to force clean memory PHP如何强制清理内存 PHP
【发布时间】:2023-04-06 00:52:01
【问题描述】:

如何在 PHP 上强制清理内存? PHP 版本:5.5

我的 symfony2 命令:

namespace NNNN\NNNN\Command;

use NNNN\NNNN\Model\Newsletter;
use NNNN\NNNN\Model\NewsletterQuery;
use NNNN\NNNN\Model\UsersNewslettersQuery;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;


class UsersNewslettersFixCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this
            ->setName('users:newsletters:fix')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $counter = 0;
        $users = UsersNewslettersQuery::create()
            ->setFormatter(\ModelCriteria::FORMAT_ON_DEMAND)
            ->find();

        foreach ($users as $user) {
            if ($city = $user->getCity()) {
                $countryId = $city->getCountryId();
            } elseif ($location = $user->getLocation()) {
                $countryId = $location->getCountryId();
            } elseif ($region = $user->getRegion()) {
                $countryId = $region->getCountryId();
            }
            if (isset($countryId)) {
                $user->setCountryId($countryId);
                $user->save();
            }
            ++$counter;
        }

        $output->writeln('Handled '.count($counter).' users');
    }
}

如何在一些迭代后强制清理内存? ++$counter 之后的 gc_collect_cycles 不会影响内存使用。

get_memory_usage 输出:

【问题讨论】:

  • 请参阅this answer 以在对象被持久化后从内存中删除它们。
  • 谢谢,但在我的示例中使用了推进。请问可以给点推进建议吗?
  • 好的,我对 Propel 没有任何建议,抱歉。
  • 我在相关主题中找到了答案:stackoverflow.com/a/11348834/1756714

标签: php symfony


【解决方案1】:

这是大多数 ORM 的普遍问题。他们倾向于使用额外的内存来提高性能。不幸的是,您偶尔会发现它们使用了太多内存。

解决方案是在遇到这些情况时不要使用 ORM。当您需要处理大量数据时,请改用 PDO 等较低级别的东西。

$dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);

$statement = $dbh->prepare("
  select * from users
  where !countryId
");
$statement->execute();

$updateStatement = $dbh->prepare("
  update user set countryId = :countryId
");
while ($user = $statement->fetchObject()) {
  // find countryId

  $updateStatement->execute(array(
    'countryId' => $countryId
  ));
}

这将只使用几 KB 的内存并且执行速度非常快(只要您在数据库中有适当的索引)。

【讨论】:

    猜你喜欢
    • 2013-04-26
    • 2011-04-07
    • 2010-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多