[英]PHP yield vs PDO fetch?
Yesterday, I've learned that PHP has a yield()
method. 昨天,我了解到PHP有一个
yield()
方法。 I was unure about its usefulness in PHP. 我不确定它在PHP中的用处。
A colleague said it could help for SQL statements returning many rows causing potential memory issues. 一位同事表示,它可以帮助SQL语句返回许多行,从而导致潜在的内存问题。 I believe he was refering to
fetchAll()
. 我相信他正在引用
fetchAll()
。 But, instead of using fetchAll()
, one can also use fetch()
and process rows one-by-one. 但是,不是使用
fetchAll()
,也可以使用fetch()
并逐个处理行。 So, yield()
is not key to solving the issue he is referring to. 因此,
yield()
不是解决他所指的问题的关键。
Am I missing something about yield()
vs fetch()
here? 我错过了关于
yield()
vs fetch()
吗? Are there more benefits to using yield()
and generators? 使用
yield()
和generator有更多好处吗?
PS: It's true that it's easier to write clean, readable and maitainable code in large applications with yield()
than with with fetch()
. PS:与使用
fetch()
相比,使用yield()
在大型应用程序中编写干净,可读和可维护的代码更容易。
So, yield() is not key to solving the issue he is referring to.
因此,yield()不是解决他所指的问题的关键。
Exactly. 究竟。
But it can let you to disguise while()
/ fetch()
sequence as a foreach()
call if you prefer to, without memory overhead as well. 但它可以让你伪装
while()
/ fetch()
序列作为foreach()
调用,如果你愿意,也没有内存开销。
However, PDO is not a very good example, because PDOStatement
already implements a traversable interface and thus can be iterated over using foreach() : 但是,PDO不是一个很好的例子,因为
PDOStatement
已经实现了一个可遍历的接口,因此可以使用foreach()进行迭代 :
$stmt = $pdo->query('SELECT name FROM users');
foreach ($stmt as $row)
{
var_export($row);
}
So let's take mysqli for the example API that can only stream results one by one.
因此,让我们将mysqli用于只能逐个传输结果的示例API。
Edit . 编辑 。 Actually, since 5.4.0 mysqli supports Traversable as well, so there is no point in using yield with mysqli_result either.
实际上, 由于5.4.0 mysqli也支持Traversable ,所以使用yield和mysqli_result也没有意义。 But meh, let's keep it for the demonstration purpose.
但是,我们保留它用于演示目的。
Let's create a generator like this 让我们创建一个像这样的生成器
function mysqli_gen (mysqli_result $res)
{
while($row = mysqli_fetch_assoc($res))
{
yield $row;
}
}
and now you can get rows using foreach without an overhead: 现在你可以使用foreach获取行而不需要开销:
$res = $mysqli->query("SELECT * FROM users");
foreach (mysqli_gen($res) as $row)
{
var_export($row);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.