find方法为什么比query($sql)慢10到20倍?

浏览:1179 发布日期:2014/09/09 分类:求助交流 关键字: 效率
查询一条记录可以用find()方法,但跟query($sql)比起来显得慢很多,可以优化吗?

测试如下:


debug_start();
$res3 = M("Material")->where("id>5")->field('id')->find();
debug_end();
dump($res3);

debug_start();
$sql = "select id from ".C('DB_PREFIX')."material where id>5 limit 1";
$res1 = M()->query($sql);
$res1 = $res1[0];
debug_end();
dump($res1);

debug_start();
$sql = "select id from ".C('DB_PREFIX')."material where id>6 order by id ASC limit 1";
$res2 = M()->query($sql);
$res2 = $res2[0];
debug_end();
dump($res2);

显示时间:
Process : Times 0.004845s Memories 28 k

array(1) {
["id"] => string(1) "6"
}

Process : Times 0.000214s Memories 0 k

array(1) {
["id"] => string(1) "6"
}

Process : Times 0.000179s Memories 0 k

array(1) {
["id"] => string(1) "7"
}

==============================

另一个测试:


debug_start();
$res3 = M("Goods")->where("id>8524")->field('id')->find();
debug_end();
dump($res3);

debug_start();
$sql = "select id from ".C('DB_PREFIX')."goods where id>8526 limit 1";
$res1 = M()->query($sql);
debug_end();
dump($res1);

debug_start();
$sql = "select id from ".C('DB_PREFIX')."goods where id>8523 order by id ASC limit 1";
$res2 = M()->query($sql);
debug_end();
dump($res2);

exit;

显示时间:
Process : Times 0.001084s Memories 5 k

array(1) {
["id"] => string(4) "8525"
}

Process : Times 0.000176s Memories 0 k

array(1) {
[0] => array(1) {
["id"] => string(4) "8527"
}
}

Process : Times 0.000191s Memories 0 k

array(1) {
[0] => array(1) {
["id"] => string(4) "8524"
}
}

==========
为了避免mysql查询缓存在起作用,
把res1,res2,res3查询的顺序改变了,也可以看到find()比query()慢很多。
最佳答案
评论( 相关
后面还有条评论,点击查看>>