Gossamer Forum
Home : General : Perl Programming :

Developers block <g>

(Page 2 of 2)
> >
Quote Reply
Re: [brewt] Developers block <g> In reply to
Thanks, Adrian. I knew it could be done as a one liner.

- wil
Quote Reply
Re: [PaulW] Developers block <g> In reply to
In Reply To:
Prove it.
OK, Paul. As you obviously don't believe me. Here goes...

I said:

$x = "12345123451234512345x456456456456y8989";
$x =~ s/\d+//g; # faster than s/\d//g

Can you see why?

And here's my reasoning:

If you use s/\d//g on that string, you will do 36 match-and-replace's.
If you use s/\d+//g, you do 3 match-and-replace's.

Running a benchmark...

Code:
wil@localhost [12:20pm] ~ #130> bleadperl -MBenchmark=cmpthese
cmpthese(-5, {
fast => sub {
my $x = "12345123451234512345x456456456456y8989";
$x =~ s/\d+//g;
},
slow => sub {
my $x = "12345123451234512345x456456456456y8989";
$x =~ s/\d//g;
}
});
__END__
Benchmark: running fast, slow for at least 5 CPU seconds...
fast: 48872.57/s (n=256581)
slow: 11055.86/s (n=60365)


Rate slow fast
slow 11056/s -- -77%
fast 48873/s 342% --

These results prove to you how much faster using \d+ is.

- wil
Quote Reply
Re: [PaulW] Developers block <g> In reply to
In Reply To:
The difference is negligible.

Substituting a few digits just using g and using \d+ will make absolutely no noticable difference.

Coding strictly doesn't mean you should use tr///; at all.

Finally! I've found it. In "The Camel", 3rd edition - page 598 under the heading "Time Efficiency". Look at the second bullet point down:

If you're deleting characters, tr/abc//d is faster than s/[abc]//g.

End of argument. :-)

- wil
> >