A problem to solve
Open source software is filled with people who like to solve problem, so, here’s a problem I hope someone here will be able to help me solve.
How can I make the subroutine, get_location, faster? It is given a resource object and a scalar representing the human-readable location type. The routine then finds all the locations for the given resource, loops through them, and returns the location whose name equals the desired type.
my $isbn = &get_location( $resource, 'ISBN' );
sub get_location {
# get the input
my $resource = shift;
my $location_type = shift;
# initialize
my $location = '';
# process each location
foreach ( $resource->resource_locations ) {
my $type = MyLibrary::Resource::Location::Type->new( id => $_->resource_location_type );
if ( $type->name eq $location_type ) {
$location = $_->location;
last;
}
}
# done
return $location
}
The problem is the code is really slow. My my partcular application each resource includes has three location, and it seems to take about .5 seconds to process the foreach loop. Since get_location is called twice for every resource, and since there are about 25 resources per batch, doing this look up takes about 25 seconds. Way too slow. What are we doing wrong!?
One Response to “A problem to solve”
Discussion Area - Leave a Comment
You must be logged in to post a comment.
Trying to find out what MyLibrary is I ended up here…
I assume the overhead is caused by the linear scanning of the resource_locations. This could be done much faster if the resource_locations where stored or transformed to a hash or something similar with $type->name as a key, so the linear search could be converted to a single lookup.