给出一个控制台命令,其中包含从数据库加载的数据集,我的脚本对API进行爬网。 当“优化”我的代码时,我注意到一些奇怪的行为:
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());
}
...
}
...
}
$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秒钟才能执行。这种方法有什么问题吗?