Posts Tagged ‘array’

Comparing arrays

Thursday, November 21st, 2013

Here are four ways to compare two arrays in Perl:

I won’t cover Array::Compare because it depends on Moose and only compares two arrays. Why in the world would anyone use Moose to achieve such a trivial task is beyond me. There is also Data::Compare, which can compare deep structures, just like Test::Deep.

Rate eq_deeply match_smart smartmatch array_comp
eq_deeply 3021/s -92% -97% -99%
match_smart 38824/s 1185% -65% -87%
smartmatch 110476/s 3557% 185% -64%
array_comp 305302/s 10007% 686% 176%

The eq_deeply method turned out to be the slowest, but keep in mind that it’s also very powerful. It does not flatten deep arrays or hases and can accurately compare all sorts of data, not just flat arrays. I’ve been even able to compare code references with Test::Deep. The array_comp method is blazingly fast but does no checking and will only work with flat arrays. If you give it a nested structure to churn it would fail to produce an accurate result. Smartmatch and match::smart are somewhere in between. They should be used as general purpose tools to match simple data as described in the documentation. Matching nested structures with them is probably not so smart – use Test::Deep or Data::Compare instead.