【原创】测试关联预载入对性能的提升效果

【原创】测试关联预载入对性能的提升效果

关联查询的预查询载入功能,主要解决了N+1次查询的问题,例如下面的查询如果有4个记录,会执行5次查询:

// 关联预载入之前
$start_time = microtime();
$list = Model\User::select([1,2,3,4]);
foreach($list as $key=>$user){
    var_dump($user->profile);
}
$diff_time = microtime() – $start_time;
var_dump($diff_time);
float0.047106

如果使用关联预查询功能,对于一对一关联来说,只有一次查询,对于一对多关联的话,就可以变成2次查询,有效提高性能。

// 关联预载入之后
$start_time = microtime();
$list = Model\User::with(‘profile’)->select([1,2,3,4]);
foreach($list as $key=>$user){
    var_dump($user->profile);
}
$diff_time = microtime() – $start_time;
var_dump($diff_time);
float0.030193

总结:预载入之后相对于预载入之前,查询速度上有显著提升,数据量越大,提升效果越明显!

查询记录如下:

// 5次查询分别为:
SELECT * FROM `user` WHERE ( `id` IN (1,2,3,4) ) AND `user`.`delete_time` IS NULL;
SELECT * FROM `profile` WHERE ( `user_id` = 1 ) AND `profile`.`delete_time` IS NULL LIMIT 1;
SELECT * FROM `profile` WHERE ( `user_id` = 2 ) AND `profile`.`delete_time` IS NULL LIMIT 1;
SELECT * FROM `profile` WHERE ( `user_id` = 3 ) AND `profile`.`delete_time` IS NULL LIMIT 1;
SELECT * FROM `profile` WHERE ( `user_id` = 4 ) AND `profile`.`delete_time` IS NULL LIMIT 1;

// 2次查询分别为:
SELECT * FROM `user` WHERE ( `id` IN (1,2,3,4) ) AND `user`.`delete_time` IS NULL;
SELECT * FROM `profile` WHERE ( `user_id` IN (1,2,3,4) ) AND `profile`.`delete_time` IS NULL;

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据