I tried to see if there were any knobs to twiddle on this one, using dragonchild’s benchmark cases.
First thing I tried: using a recursive call to alias $_. This lets you get rid of the ternary in the for list.
sub trim {
return trim( $_ ) if not @_;
@_ = @_ if defined wantarray;
for ( @_ ) { s/^\s+//, s/\s+$// }
return wantarray ? @_ : $_[ 0 ] if defined wantarray;
}
On my setup this is about 15% slower for the “inplace replacement of implicit $_” case, but ekes out a few percentage points on the other cases. But it let me proceed to switch from duplicate defined wantarray tests to a duplicate inner loop:
sub trim2 {
return trim2( $_ ) if not @_;
return map { local $_ = $_; s/^\s+//, s/\s+$//; $_ } @_
if defined wantarray;
for ( @_ ) { s/^\s+//, s/\s+$// }
}
This gets back most of the lost speed in the “inplace replacement of implicit $_” case, has roughly the same performance in other void contexts, but is also about 50% faster in many other cases, including the IMHO most important one – passing a scalar and assigning to one.
Makeshifts last the longest. |