In the DBI documentation, this is the recommended code for executing a query many times:
$sth = $dbh->prepare_cached($statement);
$sth->execute(@bind);
$data = $sth->fetchall_arrayref(@attrs);
$sth->finish;
However, I see that many* query methods allow passing a prepared and cached statement handle in place of a query string, which makes this possible:
$sth = $dbh->prepare_cached($statement);
$data = $dbh->selectall_arrayref($sth, \%attrs, @bind);
Is there anything wrong with this approach? I haven't seen it used in the wild.
FWIW, I have benchmarked these two implementations. And the second approach appears marginally (4%) faster, when querying for two consecutive rows using fetchall_arrayref in the first implementation vs selectall_arrayref in the second.
* The full list of query methods which support this are:
- selectrow_arrayref - normal method with prepared statements is fetchrow_arrayref
- selectrow_hashref - " " fetchrow_hashref
- selectall_arrayref - " " fetchall_arrayref
- selectall_hashref - " " fetchall_hashref
- selectcol_arrayref (doesn't really count, as it has no parallel method using the first code path as described above - so the only way to use prepared statements with this method is to use the second code path above)
No, there's nothing wrong that approach. There is something wrong with your benchmark or its analysis, though.
You've claimed that
is slower than a call to
Maybe if you got rid of the useless call to
finishyou'll find the first faster? Note that benchmarks with less than 5% difference are not very telling; the accuracy isn't that high.Update: s/faster than/slower than/