Smart Match – Speed comparison
Recently I was reading an article from the good folks at Perl Training Australia about the 5.10 Smart Match functionality. I was particularly interested in the fact that they referred to the speed of the Smart Match being “extremely fast”, so I decided to hack together a quick script to see what potential speed gains we were looking at.
I focused my investigation on comparing two arrays and using Benchmark to see how much quicker using the Smart Match would be.
I created two quick routines to compare the arrays:
sub smart_compare {
return 1 if(\@a ~~ \@b);
}
sub foreach_compare {
return 0 if(@a != @b); #Scalar compare to check lengths.
my $i = 0;
foreach (@a) {
return 0 if($a[$i] != $b[$i]);
++$i;
}
return 1;
}
The smart match comparison being much more concise and the foreach_compare not having an particular optimisations, but both being fairly trivial.
So I chose four simple test cases for comparing the arrays:-
- Matching arrays (1,2,3,4,5,6) == (1,2,3,4,5,6)
- Last value different (1,2,3,4,5,6) == (1,2,3,4,5,5)
- First value different (1,2,3,4,5,6) == (5,2,3,4,5,6)
- Number of items in arrays different (1,2,3,4,5,6) = (1,2,3,4,5,6,7)
I was expecting the Smart Match to be quicker, although not by too much in all of the cases. It turns out that the Smart Match was slower in all but one case (Over a million iterations).
- Matching arrays (Smart Compare: 21 Seconds Foreach Loop: 7 Seconds)
- Last value different (Smart Compare: 20 Seconds Foreach Loop: 6 Seconds)
- First value different (Smart Compare: 5 Seconds Foreach Loop: 3 Seconds)
- Number of items in arrays different (Smart Compare: 1 Second Foreach Loop: 1 Second)
When the number of items in the array is different the Smart Match and Foreach loop perform pretty much evenly across repeated tests.
All the tests were ran on Perl 5.10.0, installed from Source on a P4 with 2 Gig of ram. Whilst these findings show the smart match to be slower when comparing arrays, this is of course only a simple test case and other types of comparisons offered by the Smart Match should obviously be investigated too.
The test script is available for download if anyone wants to give it a go on their system (or find any mistakes).
0 comments
Kick things off by filling out the form below.
Leave a Comment