First, your benchmark is bogus code; shift @from for @from is not advisable. Use a while instead.
Anyway, there’s no “growable end” per se to arrays. Variables in Perl translate to multiply indirect structures in perl, which means that all of them can grow or shrink pretty seemlessly (hmm, with caveats).
Update: at first I claimed that the same is true of strings while I tried to work the kinks ouf my benchmark. It was a little tricky to do correctly because growing strings from the end with substr requires a length call that is not necessary when growing from the start. Now that I have, though, the final version disproves my expectations:
#!/usr/bin/perl
use strict;
use warnings;
use Benchmark qw( timethese cmpthese );
my $template = 1 x 200;
cmpthese timethese -5 => {
end_end => sub {
my $from = $template;
my $to = '';
for ( 0 .. 100 ) {
substr $to, length $to, 0, substr $from, -1, 1, '' while l
+ength $from;
substr $from, length $from, 0, substr $to, -1, 1, '' while
+ length $to;
}
},
start_end => sub {
my $from = $template;
my $to = '';
for ( 0 .. 100 ) {
substr $to, length $to && 0, 0, substr $from, -1, 1, '' wh
+ile length $from;
substr $from, length $from && 0, 0, substr $to, -1, 1, ''
+while length $to;
}
},
end_start => sub {
my $from = $template;
my $to = '';
for ( 0 .. 100 ) {
substr $to, length $to, 0, substr $from, 0, 1, '' while le
+ngth $from;
substr $from, length $from, 0, substr $to, 0, 1, '' while
+length $to;
}
},
start_start => sub {
my $from = $template;
my $to = '';
for ( 0 .. 100 ) {
substr $to, length $to && 0, 0, substr $from, 0, 1, '' whi
+le length $from;
substr $from, length $from && 0, 0, substr $to, 0, 1, '' w
+hile length $to;
}
},
};
__END__
Benchmark: running end_end, end_start, start_end, start_start for at l
+east 5 CPU seconds...
end_end: 6 wallclock secs ( 5.28 usr + 0.01 sys = 5.29 CPU) @ 34
+.22/s (n=181)
end_start: 5 wallclock secs ( 5.33 usr + 0.01 sys = 5.34 CPU) @ 33
+.33/s (n=178)
start_end: 6 wallclock secs ( 5.25 usr + 0.00 sys = 5.25 CPU) @ 25
+.90/s (n=136)
start_start: 5 wallclock secs ( 5.22 usr + 0.01 sys = 5.23 CPU) @ 2
+5.43/s (n=133)
Rate start_start start_end end_start end_end
start_start 25.4/s -- -2% -24% -26%
start_end 25.9/s 2% -- -22% -24%
end_start 33.3/s 31% 29% -- -3%
end_end 34.2/s 35% 32% 3% --
So while it doesn’t matter whether you’re shrinking from the start or the end of the string (no surprise), it does matter noticably which end you grow the string from. Hmm. Perl is lower-level than with other things, here.
Makeshifts last the longest. |