简体   繁体   English

Laravel 分块不会减少 PHP 内存使用

[英]Laravel chunking not reducing PHP memory usage

So I've been trying my hands on laravel's chunking in Eloquent but I've run into a problem.所以我一直在尝试在 Eloquent 中处理 laravel 的分块,但我遇到了一个问题。 Consider the following code (a much more simplified version of my problem):考虑以下代码(我的问题的更简化版本):

$data = DB::connection('mydb')->table('bigdata')
->chunk(200, function($data) {
  echo memory_get_usage();
  foreach($data as $d) {
    Model::create(
      array(
        'foo' => $d->bar,
        ...
        //etc
      ));
  }
}

So when I run the following code my memory outputs look like this:因此,当我运行以下代码时,我的内存输出如下所示:

19039816
21490096
23898816
26267640
28670432
31038840

So without jumping into php.ini and changing the memory_limit value any clue why it isn't working?因此,如果不跳入php.ini并更改memory_limit值,就没有任何线索为什么它不起作用? According to the documentation: "If you need to process a lot (thousands) of Eloquent records, using the chunk command will allow you to do without eating all of your RAM".根据文档:“如果您需要处理大量(数千)Eloquent 记录,使用 chunk 命令将使您无需占用所有 RAM”。

I tried unset($data) after the foreach function but it did not help.我在 foreach 函数之后尝试了unset($data)但它没有帮助。 Any clue as to how I can make use of chunk or did I misinterpret what it does?关于如何使用chunk任何线索还是我误解了它的作用?

Chunking data doesn't reduce memory usage, you need to do it like pagination directly using the database.分块数据不会减少内存使用量,您需要像直接使用数据库进行分页一样进行分块。

Like first fetch starting 200 order by id or something, and after processing first 200, fire that query again with a where clause asking next 200 results.就像首先按 id 或其他东西从 200 个订单开始获取,在处理前 200 个之后,使用 where 子句再次触发该查询,询问接下来的 200 个结果。

You can use lazy collections to improve memory uses for a big collection of data.您可以使用惰性集合来改善大量数据的内存使用。 It uses PHP generators under the hood.它在幕后使用 PHP 生成器。 Take a look at the cursor example here https://laravel.com/docs/5.4/eloquent#chunking-results在此处查看光标示例https://laravel.com/docs/5.4/eloquent#chunking-results

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM