I was asked by a coworker if there was an easy way to compare arrays.
| if (@a != @b) { dosomething} |
NO SUCH LUCK
So I wrote him a little snippet - which I post here for your "enjoyment"
sub compArray
# compare two arrays
# use: compArray(\@one,\@two)
# returns 1 for same 0 for different
# stupid obfuscated version
# optimised for speed - no local vars
{
if (@{$_[0]} != @{$_[1]}) { return 0; } # test lengths
foreach (0 .. @{$_[0]}) # go element by element
{
if ($_[0][$_] ne $_[1][$_]) {return 0;}
}
return 1; # If I got here we are good
} |
Ok, Why is it so hard to read, you may ask. I was told that this function was going to be called thousands of times within the code. So I wanted it to be fast. I wanted it to be slim (memory profile). So I removed all reffernces to local variables. Except an anonymous list that is the same size as the array that is being compared. Why? Becuase it runs faster than a for loop with a counter.
I ask - can anyone come up with a faster method?
The rules:
a) it cannot modify either array
b) if called with a the same array as both arguments it must return true
thus :
sub compArrayDestro
# compare two arrays
# use: compArray(\@one,\@two)
# returns 1 for same 0 for different
{
if (@{$_[0]} != @{$_[1]}) { return 0; } # test lengths
while (@{$_[0]}) {(pop(@{$_[0]}) ne pop(@{$_[1]}))?return 0:1;}
return 1; # If I got here we are good
} |
Is right out