使用私有$ var会减慢PHP中的foreach(Symfony4控制台命令)

时间:2018-10-05 12:34:59

标签: php symfony

给出一个控制台命令,其中包含从数据库加载的数据集,我的脚本对API进行爬网。 当“优化”我的代码时,我注意到一些奇怪的行为:

检索类别/ check_online

class Crawl {
    ...
    public function check_online($data){
        $settings = new Settings();
        $api = new RiotApi($settings);

        try {
            $game = $api->getCurrentGame($summoner->getSummonerId());
        } catch (RiotApiException $e) {
           throw new CrawlException($e->getMessage());
        }

        ...
    }
    ...
}

Symfony命令

$apiCrawl = new Crawl($this->em, true);

foreach($dataset as $data){
    $online= $apiCrawl ->check_online($data);
}

此操作每$data大约执行1秒

由于$api被多次使用,因此我尝试将其移至Crawl类的构造函数中:

public function __construct(ObjectManager $em)
{
    $this->em = $em;
    $settings = new Settings();
    $this->api = new RiotApi($settings);
}

并相应地更新了Symfony命令:

try {
    $game = $this->api->getCurrentGame($summoner->getSummonerId());
} catch (RiotApiException $e) {
    throw new CrawlException($e->getMessage());
}

现在,这大约需要10秒钟才能执行。这种方法有什么问题吗?

0 个答案:

没有答案
相关问题