我正在try 编写一个laravel函数,该函数从一个数据库获取大量记录(100,000+),然后将其放入另一个数据库.为此,我需要查询我的数据库并查看该用户是否已经存在.我反复调用这个代码:
$users = User::where('id', '=', 2)->first();
然后,在这种情况发生几百次之后,我的记忆就耗尽了.所以,我做了一个极简主义的例子,它使用了所有可用的内存,看起来是这样的:
<?php
use Illuminate\Console\Command;
class memoryleak extends Command
{
protected $name = 'command:memoryleak';
protected $description = 'Demonstrates memory leak.';
public function fire()
{
ini_set("memory_limit","12M");
for ($i = 0; $i < 100000; $i++)
{
var_dump(memory_get_usage());
$this->external_function();
}
}
function external_function()
{
// Next line causes memory leak - comment out to compare to normal behavior
$users = User::where('id', '=', 2)->first();
unset($users);
// User goes out of scope at the end of this function
}
}
这个脚本的输出(由'php artisan command:memoryleak'执行)如下所示:
int(9298696)
int(9299816)
int(9300936)
int(9302048)
int(9303224)
int(9304368)
....
int(10927344)
int(10928432)
int(10929560)
int(10930664)
int(10931752)
int(10932832)
int(10933936)
int(10935072)
int(10936184)
int(10937320)
....
int(12181872)
int(12182992)
int(12184080)
int(12185192)
int(12186312)
int(12187424)
PHP Fatal error: Allowed memory size of 12582912 bytes exhausted (tried to allocate 89 bytes) in /Volumes/Mac OS/www/test/vendor/laravel/framework/src/Illuminate/Database/Connection.php on line 275
If I comment out the line "$users = User::where('id', '=', 2)->first();" then the memory usage stays stable.
Does anyone have any insight as to why this line would use memory like this, or know a smarter way to accomplish what I am trying to do?
谢谢你抽出时间.