in reply to Can this code be optimized further?
I'd go with BrowserUK's code :)#!/usr/bin/perl -w use strict; use Time::HiRes qw( gettimeofday tv_interval); my @temp=("a_1","b_1","a_2","a_3","a_4","b_2","a_5","b_3","a_6","b_4") +; my @startTime = gettimeofday; for ( 1..10000 ) { my (@a, @b) ; foreach my $value (@temp) { push @a, $1 if ($value =~ /a_(.*)/) ; push @b, $1 if ($value =~ /b_(.*)/) ; } } print "Time: ".tv_interval( \@startTime )."\n"; @temp = qw( a_1 b_1 a_2 a_3 a_4 b_2 a_5 b_3 a_6 b_4 ); @startTime = gettimeofday; for ( 1..10000 ) { my %values; foreach (@temp) { /^([ab])_(.*)/ && do { push @{$values{$1}}, $2; next; }; die "'$_' doesn't match the pattern of ^[ab]_.*\n"; } } print "Time: ".tv_interval( \@startTime )."\n"; @temp = qw( a_1 b_1 a_2 a_3 a_4 b_2 a_5 b_3 a_6 b_4 ); @startTime = gettimeofday; for ( 1..10000 ) { my (@a, @b); foreach (@temp) { my $prefix = substr( $_, 0, 2 ); if ( $prefix eq 'a_' ) { push @a, substr( $_, 2 ); } elsif ( $prefix eq 'b_' ) { push @b, substr( $_, 2 ); } } } print "Time: ".tv_interval( \@startTime )."\n"; @startTime = gettimeofday; for ( 1..10000 ) { my( @a, @b ); my %arrays; eval qq{\$arrays{ "$_" } = \\\@$_} for qw( a b ); for( @temp ) { die "Invalid prefix on element '$_'\n" unless /^([ab])_(.*)/; push @{ $arrays{ $1 } }, $2; } } print "Time: ".tv_interval( \@startTime )."\n"; @startTime = gettimeofday; for ( 1..10000 ) { my @a = map {/a_(.*)/ ? $1 : ()} @temp; my @b = map {/b_(.*)/ ? $1 : ()} @temp; } print "Time: ".tv_interval( \@startTime )."\n"; @startTime = gettimeofday; for ( 1..10000 ) { my @a_arr = grep { s/^a_(.*)/$1/} @temp; my @b_arr = grep { s/^b_(.*)/$1/} @temp; } print "Time: ".tv_interval( \@startTime )."\n"; # GAVE ME substr outside of string at ./testme2.pl line 88. #@startTime = gettimeofday; #for ( 1..10000 ) { # my %parts; # push @{ $parts{ substr $_, 0, 1 }}, substr $_, 2 # foreach @temp; #} #print "Time: ".tv_interval( \@startTime )."\n"; @startTime = gettimeofday; for ( 1..10000 ) { my (@a, @b) ; m[^([ab])_(.*)$] and push @{$1 eq 'a' ? \@a : \@b}, $2 for @temp; } print "Time: ".tv_interval( \@startTime )."\n"; Output: Time: 0.575739 Time: 0.717803 Time: 0.46604 Time: 1.731715 Time: 0.777471 Time: 0.462416 Time: 0.103439
Baseline Time: 0.584196 Regexp w/ Hash Time: 0.7385 Eval Time: 1.774581 Map Time: 0.76179 Grep Time: 0.456991 Hash w/ substr Time: 0.411059 Regexp w/ eq Time: 0.683154 Router Time: 0.668033
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Can this code be optimized further?
by eric256 (Parson) on Feb 10, 2005 at 16:10 UTC | |
by Roy Johnson (Monsignor) on Feb 10, 2005 at 18:08 UTC | |
by dragonchild (Archbishop) on Feb 10, 2005 at 18:35 UTC | |
by Roy Johnson (Monsignor) on Feb 10, 2005 at 18:52 UTC | |
by RazorbladeBidet (Friar) on Feb 10, 2005 at 16:18 UTC | |
by eric256 (Parson) on Feb 10, 2005 at 16:33 UTC | |
by RazorbladeBidet (Friar) on Feb 10, 2005 at 16:37 UTC |