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

perrin has asked for the wisdom of the Perl Monks concerning the following question:

I'm benchmarking the latest SQLite for use in sharing data between mod_perl processes. The use case is a shared hash, which is modeled as a single table with columns "a_key" and "value". However, my code is running pretty slow. Simple MySQL code doing the same thing goes three times as fast, and BerkeleyDB goes about 17 times as fast. I'm wondering if SQLite is really this slow, or if I'm just not aware of some important tuning step with it. Removing the commit after storing data makes it three times as fast, but then it's no longer doing something comparable to the MySQL and BDB code since other processes would not be able to see that data.

The SQLite part of my test code is below. I just bang on this with a couple of hundred thousand hits to store() and fetch() and see how long it takes. I'm using the latest DBI and DBD::SQLite.

package IPC::SharedHash::DBDSQLite; use strict; use warnings; use DBI; use DBD::SQLite; use Storable qw(nfreeze thaw); my $DB_NAME = 'SQLite'; sub new { my $class = shift; my $self = {}; my %options = @_; $self->{'SCALARS_ONLY'} = 1; my $dbh = DBI->connect_cached( 'dbi:SQLite:dbname=' . $options{'DIRECTORY'} . '/' . $DB_NAME, '', '', { AutoCommit => 0 }) || die; $dbh->{'RaiseError'} = 1; $dbh->do('PRAGMA synchronous = OFF'); unless ( $dbh->tables( '', '', 'shared_hash', '' ) ) { $dbh->do( 'create table shared_hash ( a_key text primary key, value +text )'); } my $fetch_sth = $dbh->prepare('select value from shared_hash where a_key = ?'); my $store_sth = $dbh->prepare('replace into shared_hash (a_key, value) values (? +, ?)'); $self->{'dbh'} = $dbh; $self->{'fetch'} = $fetch_sth; $self->{'store'} = $store_sth; bless $self, $class; return $self; } sub fetch { my $self = shift; my ($key) = @_; $self->{'fetch'}->execute($key); my $value; $self->{'fetch'}->bind_columns( \$value ); $self->{'fetch'}->fetch(); $self->{'fetch'}->finish(); if ( $self->{'SCALARS_ONLY'} ) { return $value; } else { if ( defined $value ) { return thaw($value); } } } sub store { my $self = shift; my ( $key, $value ) = @_; if ( !$self->{'SCALARS_ONLY'} ) { warn $self->{'SCALARS_ONLY'}; $value = nfreeze($value); } $self->{'store'}->execute( $key, $value ); $self->{'dbh'}->commit(); } sub DESTROY { my $self = shift; $self->{'dbh'}->disconnect(); } 1;
... and here's a small sample of calling it:
#!/usr/bin/perl use strict; use warnings; use IPC::SharedHash::DBDSQLite; my $hash = IPC::SharedHash::DBDSQLite->new( DIRECTORY => '/tmp', SCALARS_ONLY => 1, ); for ( 0 .. 10000 ) { $hash->store( "key$_", $_ ); my $return = $hash->fetch("key$_"); die "bad return: $return" unless $return == $_; }