I often have to filter elements of an array
of strings, containing some substring (e.g. one character). Since it can be done either by matching a regex
or with .contains
method, I've decided to make a small test to be sure that .contains
is faster (and therefore more appropriate).
my @array = "aa" .. "cc";
my constant $substr = 'a';
my $time1 = now;
my @a_array = @array.grep: *.contains($substr);
my $time2 = now;
@a_array = @array.grep: * ~~ /$substr/;
my $time3 = now;
my $time_contains = $time2 - $time1;
my $time_regex = $time3 - $time2;
say "contains: $time_contains sec";
say "regex: $time_regex sec";
Then I change the size of @array
and the length of $substr
and compare the times which each method took to filter the @array
. In most cases (as expected), .contains
is much faster than regex
, especially if @array
is large. But in case of a small @array
(as in the code above) regex
is slightly faster.
contains: 0.0015010 sec
regex: 0.0008708 sec
Why does this happen?