gpt4 book ai didi

php - 为什么PHP Mysql multi_query()比loop query()慢

转载 作者:行者123 更新时间:2023-11-29 21:25:28 24 4
gpt4 key购买 nike

我正在使用 MySQL 开发 HHVM。我真的很困惑地发现使用 multi_query() 批处理 2000 个 sql 查询比使用单个 query() 批处理 2000 个循环慢得多(请参阅最后的代码和结果)。通过进一步分析,我发现 API next_result() 占用了大部分时间(~70%)。

我的问题是:
(1) 为什么API next_result() 这么慢?
(2)如果我想一起做数千个sql查询,有没有比naive循环更好的方法?
谢谢!

这是代码(php):

$conn = new mysqli("localhost", "root", "pwd", "table");

$loop = 2000;
$q = "select * from ContactInfo;";

// single query in a loop
$results = array();
$sq_start = microtime(true);
for ($i=0; $i < $loop; $i++) {
$ret = $conn->query($q);
$results[] = $ret;
}
for ($i=0; $i < $loop; $i++) {
$xx = $results[$i]->fetch_all();
}
$sq_end = microtime(true);

// construct the multi-query
for ($i=0; $i < $loop; $i++) {
$m_q .= $q;
}

// multi-query in one round-trip
$mq_start = microtime(true);
$conn->multi_query($m_q);
do {
$ret = $conn->store_result();
$xx = $ret->fetch_all();
} while($conn->next_result());
$mq_end = microtime(true);

echo "Single query: " . ($sq_end - $sq_start)*1000 . " ms\n";
echo "Multi query: " . ($mq_end - $mq_start)*1000 . " ms\n";

结果如下:

Single query: 526.38602256775 ms
Multi query: 1408.7419509888 ms

注意:在这种情况下,next_result() 将消耗 922 毫秒。

最佳答案

这里最简单的答案是开销。 multi_query() 为每个结果集构建一个数据对象。然后它必须一遍又一遍地存储该对象。

相比之下,您一遍又一遍地运行相同的查询,但只编写一个简单的数据数组来存储结果。然后,PHP 可以释放先前结果集的内存,因为您不断地覆盖相同的变量(一旦数据对象内部没有任何内容指向它,它可能是 garbage collected )。

但这并不是一个很好的用例。这里没有现实世界的应用程序,因为不需要一遍又一遍地运行相同的查询(您的数据库应该缓存第一次运行的结果,然后将数据存储在内存中以便更快地检索)。 对于单个结果集,此处的差异可以忽略不计。

关于php - 为什么PHP Mysql multi_query()比loop query()慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35531583/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com