|There's more than one way to do things|
Re: Simply Too Slow Find and Replaceby ariels (Curate)
|on Jun 03, 2002 at 06:43 UTC||Need Help??|
The chief cause of your program wasting time is that it recompiles every pattern for every replacement. It's better to do it just once, before processing commences. The correct abstraction for a substitution is a code ref (an "anonymous sub"). You pre-compile all your subs, then blast each string through them all.
UPDATE: Fixed stupid bugs in code. ``Engage brain before posting on the Internet!''
This code compares your code (fixed to use the clearer, better form push) with 2 ways of precompiling:
We only benchmark a single iteration, because <samp>new</samp> and <samp>new2</samp> should only build their subroutines once. In your real program, you'd build the array <samp>@replacer</samp> once, then re-use it for every record.
Also note that <samp>\Q...\E</samp> doesn't speed up the substitutions.
On one computer, the benchmark gives:
If you read the above code before, please note again this UPDATE: Fixed stupid bugs in code. ``Engage brain before posting on the Internet!''Benchmark: timing 1 iterations of new, new2, old... new: 9 wallclock secs ( 8.44 usr + 0.14 sys = 8.58 CPU) @ 0.12/s (n=1) (warning: too few iterations for a reliable count) new2: 8 wallclock secs ( 7.97 usr + 0.07 sys = 8.04 CPU) @ 0.12/s (n=1) (warning: too few iterations for a reliable count) old: 30 wallclock secs (30.46 usr + 0.09 sys = 30.55 CPU) @ 0.03/s (n=1) (warning: too few iterations for a reliable count) Done