in reply to Replace all . with _ in a string

While it probably doesn't matter much in many real world situations, I think it's worth mentioning that the tr/// method of transliterating single characters is much more efficient than the s///g method. s///g is, of course, a good way to do it if you're trying to work on multiple characters or complex situations. But for simple "dumb" single-character replacement, tr/// is the right tool for the job.

The following takes a string of 10,000 characters, and changes all of the characters to an alternate character, and then changes them back to their original state... and repeats that approach 5,000 times for each operator (tr/// and s///g). The results are dramatic, but in real world applications how many times are you going to be performing 5000 iterations of replacing 10,000 single characters? ;)

use strict; use warnings; use Benchmark; my $string = '.' x 10000; sub tr_test { $string =~ tr/./_/; $string =~ tr/_/./; } sub s_test { $string =~ s/\./_/g; $string =~ s/_/./g; } my $count = 5000; timethese ( $count, { 'TR' => \&tr_test, 'S' => \&s_test } ); __OUTPUT__ Benchmark: timing 5000 iterations of S, TR... S: 48 wallclock secs (46.95 usr + 0.01 sys = 46.96 CPU) @ 106.48/s (n=5000) TR: 0 wallclock secs ( 0.58 usr + 0.00 sys = 0.58 CPU) @ 8605.85/s (n=5000)

The speed difference is both understandable and breathtaking. And in some applications it might even matter, while in others, it might not. ;)


Dave