Bri*_*son 18 laravel laravel-4
我正在尝试编写一个laravel函数,它从一个数据库中获取大量记录(100,000+)并将其放入另一个数据库中.为此,我需要查询我的数据库,看看用户是否已经存在.我反复调用这段代码:
$users = User::where('id', '=', 2)->first();
Run Code Online (Sandbox Code Playgroud)
然后在那之后发生几百次,我的内存耗尽.所以,我做了一个极简主义的例子,它耗尽了所有可用的内存,它看起来像这样:
<?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
}
}
Run Code Online (Sandbox Code Playgroud)
这个脚本的输出(由'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
Run Code Online (Sandbox Code Playgroud)
如果我注释掉"$ users = User :: where('id','=',2) - > first();" 那么内存使用率保持稳定.
有没有人知道为什么这条线会使用这样的内存,或者知道一种更聪明的方法来完成我想做的事情?
感谢您的时间.
Eri*_*rik 41
我重新创建了你的脚本并使用调试器逐步完成它,因为我无法理解什么样的可怕事情会导致这种类型的内存问题.当我走过时,我遇到了这个:
// in Illuminate\Database\Connection
$this->queryLog[] = compact('query', 'bindings', 'time');
Run Code Online (Sandbox Code Playgroud)
看起来您在Laravel中运行的每个查询都存储在持久日志中,这解释了每次查询后内存使用量的增加.就在上面,是以下行:
if ( ! $this->loggingQueries) return;
Run Code Online (Sandbox Code Playgroud)
稍微挖掘确定loggingQueries
默认情况下该属性设置为true,并且可以通过该disableQueryLog
方法更改,这意味着,如果您调用:
DB::connection()->disableQueryLog();
Run Code Online (Sandbox Code Playgroud)
在你要执行所有查询之前,你不会看到不断增加的内存使用量; 它根据您的示例代码运行我的测试时解决了问题.完成后,如果您不想影响可以调用的应用程序的其余部分
DB::connection()->enableQueryLog();
Run Code Online (Sandbox Code Playgroud)
可重新登录.
归档时间: |
|
查看次数: |
11535 次 |
最近记录: |