0

In Perl search and replace with large variables takes a long time.

For example.

$original = 'aaaabc';
$replace = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' x 1000
$original =~ s/b/$replace/;

Once $replace is of large enough size the regex can take a seriously long time. I assume some buffer is breached and keeps getting extended.

Is there any suggestions to improve performance?

3 Answers 3

3

How large is large? The substitution takes place within a second on my Windows box, even with a string of length 30,000,000 30,000,000,000,000,000,000:

> perl -Mstrict -wE "my $start = time;my $str = 'aaaabc'; my $replace = 'b' x 30_000_000_000_000_000_000; $str =~ s/b/$replace/; printf qq<%d s\n>, time - $start;"
0 s
1

Not sure why you're seeing performance degradation. I made a string for replace of 50000+ characters, and then ran your program as written.

$ time(perl large.pl )

real    0m0.010s
user    0m0.002s
sys     0m0.004s
$ 

However, I do have a suggestion. If your replacement string is a finite length of the same character, why not find the particular character in your original string, split the string upon that character, and join the parts to the front and back of your replacement, and print it out?

0
Benchmark gives 0 wallclock secs with your input 

#!/usr/bin/perl
use strict;
use warnings;
use Benchmark;

my $original = 'aaaabcd';
my $replace = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' x 1000;
my $start_time = new Benchmark;
$original =~ s/b/$replace/;
my $end_time = new Benchmark;
my $diff = timediff($end_time,$start_time);
print "Regex took:",timestr($diff);

OUTPUT

Regex took 0 wallclock secs (0.00 usr + 0.00 sys = 0.00 CPU)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.