PDO :: fetchAll与PDO :: fetch在循环中

编程入门 行业动态 更新时间:2024-10-28 03:23:26
本文介绍了PDO :: fetchAll与PDO :: fetch在循环中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

一个简单的问题.

在循环中(对于大型结果集)使用PDO :: fetchAll()和PDO :: fetch()之间是否存在性能差异?

Is there any performance difference between using PDO::fetchAll() and PDO::fetch() in a loop (for large result sets)?

我正在获取用户定义类的对象,如果有什么不同的话.

I'm fetching into objects of a user-defined class, if that makes any difference.

我最初的未经教育的假设是fetchAll可能会更快,因为PDO可以在一条语句中执行多个操作,而mysql_query只能执行一条.但是,我对PDO的内部工作原理知之甚少,文档也对此一无所知,而fetchAll()是否只是转储到数组中的PHP端循环.

My initial uneducated assumption was that fetchAll might be faster because PDO can perform multiple operations in one statement while mysql_query can only execute one. However I have little knowledge of PDO's inner workings and the documentation doesn't say anything about this, and whether or not fetchAll() is simply a PHP-side loop dumped into an array.

有帮助吗?

推荐答案

具有200k个随机记录的小基准.正如预期的那样,fetchAll方法更快,但需要更多的内存.

Little benchmark with 200k random records. As expected, the fetchAll method is faster but require more memory.

Result : fetchAll : 0.35965991020203s, 100249408b fetch : 0.39197015762329s, 440b

使用的基准代码:

<?php // First benchmark : speed $dbh = new PDO('mysql:dbname=testage;dbhost=localhost', 'root', ''); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql = 'SELECT * FROM test_table WHERE 1'; $stmt = $dbh->query($sql); $data = array(); $start_all = microtime(true); $data = $stmt->fetchAll(); $end_all = microtime(true); $stmt = $dbh->query($sql); $data = array(); $start_one = microtime(true); while($data = $stmt->fetch()){} $end_one = microtime(true); // Second benchmark : memory usage $stmt = $dbh->query($sql); $data = array(); $memory_start_all = memory_get_usage(); $data = $stmt->fetchAll(); $memory_end_all = memory_get_usage(); $stmt = $dbh->query($sql); $data = array(); $memory_end_one = 0; $memory_start_one = memory_get_usage(); while($data = $stmt->fetch()){ $memory_end_one = max($memory_end_one, memory_get_usage()); } echo 'Result : <br/> fetchAll : ' . ($end_all - $start_all) . 's, ' . ($memory_end_all - $memory_start_all) . 'b<br/> fetch : ' . ($end_one - $start_one) . 's, ' . ($memory_end_one - $memory_start_one) . 'b<br/>';

更多推荐

PDO :: fetchAll与PDO :: fetch在循环中

本文发布于:2023-10-26 20:34:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531275.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:PDO   fetchAll   fetch

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!