http://www.perlmonks.org?node_id=92125


in reply to Re: Re:{2} Leashing DBI
in thread Leashing DBI

prepare_cached() (and other similar tricks of reusing the same statement handle to avoid reparsing the same SQL statement) doesn't give any performance benefit if the underlying database doesn't support that, i.e. MySQL.

For DBD::mysql, when we call $sth->execute, the driver will eventually call mysql_real_query() which reparses the same SQL statement. Placeholders are emulated by the driver.
The following is a simple test which compares the performance between using of reusable $sth and using the "unrecommended" way. With DBD::mysql, of course:

my $res = $dbh->selectall_arrayref(<<'SQL'); SELECT id, title FROM tbl_articles SQL my @subs = ( [ 'Using string subst' => sub { for (@$res) { $dbh->do( 'UPDATE tbl_articles SET title = '. $dbh->quote('##'.$_->[1])." WHERE id = $_->[0]"); } }, ], [ 'Using placeholders' => sub { my $sth = $dbh->prepare(<<'SQL'); UPDATE tbl_articles SET title = ? WHERE id = ? SQL for (@$res) { $sth->execute(@{$_}[1,0]); } }, ], ); for (@subs) { print "$_->[0]:\n"; timethis(100, $_->[1]); }
And my result:
Using string subst: timethis 100: 15 wallclock secs ( 2.33 usr + 0.78 sys = 3.11 CPU) Using placeholders: timethis 100: 15 wallclock secs ( 2.45 usr + 0.97 sys = 3.42 CPU)

So if we stuck to MySQL, we needn't worry about placholders, prepare_cached() or something like that. No performance penalty for not harnessing them.

I agree with you about sacrificing performance for 'beauty' of code. This even worse for wrapper modules (around DBI) which try to add more database independency than that provided by DBI. Take a look of how DBIx::Recordset solves the problem of alleviating different ways of each DBMS of doing partial select. Really unsatisfactory from performance standpoint.