in reply to Replace all . with _ in a string
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
|
|---|