#!/usr/bin/perl -w use strict; use Benchmark qw/cmpthese/; my @temp=("a_1","b_1","a_2","a_3","a_4","b_2","a_5","b_3","a_6","b_4"); # samy_kumar sub original { my (@a, @b) ; foreach my $value (@temp) { push @a, $1 if ($value =~ /a_(.*)/) ; push @b, $1 if ($value =~ /b_(.*)/) ; } } # dragonchild sub hash_style { my %values; foreach (@temp) { /^([ab])_(.*)/ && do { push @{$values{$1}}, $2; next; }; } } # roy jonhson sub router_style { my (@a, @b); my %router = (a => \@a, b => \@b); foreach my $value (@temp) { push @{$router{$1}}, $2 if $value =~ /([ab])_(.*)/; } } sub switch_style { 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 ); } } } sub map_style { my @a = map {/a_(.*)/ ? $1 : ()} @temp; my @b = map {/b_(.*)/ ? $1 : ()} @temp; } sub grep_style { my @a_arr = grep { s/^a_(.*)/$1/} @temp; my @b_arr = grep { s/^b_(.*)/$1/} @temp; } sub grep_map_style { my @a = map {/a_(.*)/; $1} grep /a_/, @temp; my @b = map {/b_(.*)/; $1} grep /b_/, @temp; } sub trinary { my (@a, @b) ; m[^([ab])_(.*)$] and push @{$1 eq 'a' ? \@a : \@b}, $2 for @temp; } cmpthese( 100_000, { "Original" => \&original, "Hash" => \&hash_style, "Router" => \&router_style, "Switch" => \&switch_style, "Map" => \&map_style, "Grep" => \&grep_style, "Grep + Map" => \&grep_map_style, "Trinary" => \&trinary }); __DATA__ C:\test>perl 429768.pl Rate Grep Switch Map Router Original Grep + Map Hash Trinary Grep 32489/s -- -67% -70% -78% -81% -83% -85% -87% Switch 98425/s 203% -- -9% -34% -42% -49% -55% -60% Map 108460/s 234% 10% -- -27% -36% -44% -51% -56% Router 149031/s 359% 51% 37% -- -12% -23% -32% -40% Original 168634/s 419% 71% 55% 13% -- -13% -23% -32% Grep + Map 194175/s 498% 97% 79% 30% 15% -- -12% -21% Hash 220264/s 578% 124% 103% 48% 31% 13% -- -11% Trinary 246914/s 660% 151% 128% 66% 46% 27% 12% -- C:\test>perl 429768.pl Rate Grep Switch Map Router Original Grep + Map Hash Trinary Grep 32658/s -- -66% -69% -78% -81% -83% -85% -86% Switch 95602/s 193% -- -10% -36% -43% -49% -55% -60% Map 106610/s 226% 12% -- -28% -37% -43% -50% -55% Router 148810/s 356% 56% 40% -- -12% -21% -30% -37% Original 168350/s 415% 76% 58% 13% -- -11% -21% -29% Grep + Map 188324/s 477% 97% 77% 27% 12% -- -12% -21% Hash 213220/s 553% 123% 100% 43% 27% 13% -- -10% Trinary 236967/s 626% 148% 122% 59% 41% 26% 11% -- C:\test>perl 429768.pl Rate Grep Switch Map Router Original Grep + Map Hash Trinary Grep 32819/s -- -66% -69% -78% -81% -82% -86% -87% Switch 96899/s 195% -- -9% -35% -42% -47% -58% -61% Map 106724/s 225% 10% -- -28% -37% -42% -53% -57% Router 148810/s 353% 54% 39% -- -12% -19% -35% -40% Original 168350/s 413% 74% 58% 13% -- -8% -26% -32% Grep + Map 182815/s 457% 89% 71% 23% 9% -- -20% -26% Hash 228833/s 597% 136% 114% 54% 36% 25% -- -7% Trinary 246305/s 650% 154% 131% 66% 46% 35% 8% -- C:\test>