Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP如何在长循环中清除内存?_Php_Mysql_Laravel_Memory_Memory Management - Fatal编程技术网

PHP如何在长循环中清除内存?

PHP如何在长循环中清除内存?,php,mysql,laravel,memory,memory-management,Php,Mysql,Laravel,Memory,Memory Management,我正在创建一个脚本来模拟曲棍球比赛。所有游戏每天模拟一次。然而,当我运行模拟器时,在大约50个游戏模拟之后,我得到一个错误 PHP致命错误:已耗尽268435456字节的允许内存大小 我尝试在每个游戏模拟后使用unset()函数清除内存,但似乎没有帮助。我会错过什么?我应该使用某种析构函数,还是有其他php函数可以帮助清理内存 class GameSimulatorHelper extends Model { public function run() { //

我正在创建一个脚本来模拟曲棍球比赛。所有游戏每天模拟一次。然而,当我运行模拟器时,在大约50个游戏模拟之后,我得到一个错误

PHP致命错误:已耗尽268435456字节的允许内存大小

我尝试在每个游戏模拟后使用unset()函数清除内存,但似乎没有帮助。我会错过什么?我应该使用某种析构函数,还是有其他php函数可以帮助清理内存

class GameSimulatorHelper extends Model
{
    public function run()
    {
        // Get all the games from the database.
        $games = Game::all();

        // Simulate each game.
        foreach ($games as $g) {
            $sim = new GameSimulator();
            $sim->run($g);
            unset($sim);
        }
    }
}

class GameSimulator extends Model
{
    public $homeGoals = 0;
    public $awayGoals = 0;
    // A bunch of other class variables here.

    public function run($game)
    {
        $this->simulate($game);
        // This function just resets all the class variables for the next game to be simulated.
        $this->resetSimulator();
        echo 'MEMORY USAGE: '.memory_get_usage(true) . "\n";
    }

    public function simulate()
    {
        $maxPeriods = 3;
        for ($p=1; $p <= $maxPeriods; $p++) {
            for ($i=1; $i <= 1200; $i++) {
                // Do many things here like get and set data in database.
            }
        }
    }
    // Many other functions below.
}
class GameSimulatorHelper扩展模型
{
公共功能运行()
{
//从数据库中获取所有游戏。
$games=游戏::全部();
//模拟每个游戏。
foreach($g游戏){
$sim=新游戏模拟器();
$sim->run($g);
未结算($sim);
}
}
}
类游戏模拟器扩展模型
{
公共$homeGoals=0;
公共$awayGoals=0;
//这里还有一些其他的类变量。
公开活动(游戏)
{
$this->simulate($game);
//这个函数只是为下一个要模拟的游戏重置所有类变量。
$this->resetSimulator();
回显“内存使用率:”。内存使用率(true)。“\n”;
}
公共函数模拟()
{
$maxPeriods=3;

对于($p=1;$p,我不会说这被标记为重复,但他的问题的解决方案是在这种情况下使用for循环而不是foreach…类GameSimulatorHelper扩展模型{public function run(){//从数据库获取所有游戏。$games=Game::all();$gamesCount=count($games);//模拟每个游戏。对于($i=0;$i<$gamesCount;$i++){$sim=new gamessimulator();$sim->run($games[$i]);}}@giollianosulit是什么让你说一个
for
循环会消耗更少的内存?如果所有的游戏都提前加载,那就没关系了,不是吗?我认为“做很多事情”或“很多其他功能”更可能出现漏洞位…请参见此处了解
for
vs
foreach
。也许每次尝试一个单例而不是实例化
GameSimulator
类?此外,您在上一次
for
inside
simulate()
中所做的任何事情都会对使用的内存产生很大影响。