PDO 存储 FetchAll 导致变量 vs 直接在 foreach 中使用

PDO storing FetchAll result in variable vs using directly in foreach

所以我产生了好奇心。我总是尽量避免创建只会使用一次的变量,而是尝试直接使用它(除非它是很多文本,例如 MySQL 查询)。

我平时的做法是这样的:

$getSomethingSql = 'LONG SQL';
$getSomething = $dbConnection->prepare($getSomethingSql); // or query if no parameters are needed
// Some binds etc if needed
$getSomething->execute(); // if prepared statements are used
$something = $getSomething->fetchAll(PDO::FETCH_ASSOC);

foreach ($something as $s) {}

现在,$getSomethingSql 仅使用一次,但作为变量存储,因为它可以是一个长字符串,因此看起来更好。但是,我很好奇使用上面的代码与下面的代码相比是否有任何优势:

$getSomethingSql = 'LONG SQL';
$getSomething = $dbConnection->prepare($getSomethingSql); // or query if no parameters are needed
// Some binds etc if needed
$getSomething->execute(); // if prepared statements are used

foreach ($getSomething->fetchAll(PDO::FETCH_ASSOC) as $s) {}

这两个代码是一样的吗?是否存在(巨大的)性能差异,或者其中之一更清洁?

在内部他们也会做同样的事情。唯一的区别是,在一种情况下,它将使用您显式创建的变量来保存 fetchAll() 的结果,而在第二种情况下,它将使用一个临时变量。