in reply to Re: Re (tilly) 1: Efficiency Question
in thread Efficiency Question
Fastest and smallest are incompatible.
Also do you need at least 30, or exactly?
If I wanted to be bare bones I would do something like this untested code:
Note that I go over 30 here, but doing so makes the actual lookup much faster.use strict; use vars qw($max_size $reset_size); $max_size = 60; $reset_size = 30; { my %count; my %cache; sub get_elem { my $id = shift; if (exists $count{$id}) { ++$count{$id}; return $cache{$id}; } else{ return; } } my $size; sub set_elem { { my $id = shift; my $elem = shift; if (exists $count{$id}) { $cache{$id} = $elem; } else { if ($max_size < ++$size) { _clear_cache(); } $count{$id} = 0; $cache{$id} = $elem; } redo if @_; } } sub _clear_cache { my @ids = sort {$count{$b} <=> $count{$a}} keys %count; @ids = @ids[0..($reset_size-1)]; my %new; %count = (); foreach (@ids) { $new{$_} = $cache{$_}; $count{$_} = 0; } %cache = %new; $size = $reset_size; } }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Re (tilly) 3: Efficiency Question
by MeowChow (Vicar) on Feb 24, 2001 at 01:56 UTC |
In Section
Seekers of Perl Wisdom