http://qs321.pair.com?node_id=516295


in reply to Re: add a character at the end of a string
in thread add a character at the end of a string

I didn't use a regex, as other examples given suggest, because we know the position and the character to check for, using the regex engine seemed overkill to me

I this case, it's a fixed length string, at the end of the string, so it's a rather efficient match with regex -- if you were really concerned with speed, you'd have not wanted to append an empty string when you didn't have to:

sub use_substr { my $string = shift; $string .= substr($string, -1) eq "/" ? "" : "/"; return $string; } sub use_if_substr { my $string = shift; $string .= '/' if substr($string, -1) ne "/"; return $string; } sub use_if_regex { my $string = shift; $string .="/" if(not $string =~/\/$/ ); return $string; } sub use_regex { my $string = shift; $string =~ s|/?$|/|; return $string; } use Benchmark 'cmpthese'; my @strings = ( qw( a / sdf/ /some/path /another/path/ sdfasdfasdfsdaf +sadfasdfsfdsadfsdfsdfsadfasdfsadfsadfsadfsadfsdfsadfasfsdafasdfsdf ), + 'some string with spaces in it' ); cmpthese ( 100000, { 'if_substr' => sub { use_if_substr($_) for @strings }, 'substr' => sub { use_substr($_) for @strings }, 'if_regex' => sub { use_if_regex($_) for @strings }, 'regex' => sub { use_regex($_) for @strings } } );

Results in:

Benchmark: timing 100000 iterations of if_regex, if_substr, regex, sub +str... if_regex: 3 wallclock secs ( 2.50 usr + 0.00 sys = 2.50 CPU) @ 40 +000.00/s (n=100000) if_substr: 2 wallclock secs ( 2.47 usr + 0.00 sys = 2.47 CPU) @ 40 +485.83/s (n=100000) regex: 5 wallclock secs ( 4.88 usr + 0.00 sys = 4.88 CPU) @ 20 +491.80/s (n=100000) substr: 4 wallclock secs ( 2.57 usr + 0.00 sys = 2.57 CPU) @ 38 +910.51/s (n=100000) Rate regex substr if_regex if_substr regex 20492/s -- -47% -49% -49% substr 38911/s 90% -- -3% -4% if_regex 40000/s 95% 3% -- -1% if_substr 40486/s 98% 4% 1% --

In my opinion, it's a case of premature optimization, as with the differences so insignificant for the top three, it's not worth worrying about. (multiple runs don't have a consistent leader, and variations in versions of perl might cause different results) ... and odds are, this one replacement is a very small part of the overall program, so I wouldn't even be opposed to the slowest one, as it's the shortest to type.