Reply to topic
Stupid little tip
spandox


Joined: 03 Jul 2004
Posts: 17
Location: Delaware
Reply with quote
I was asked by a coworker if there was an easy way to compare arrays.
Code:
if (@a != @b) { dosomething}

NO SUCH LUCK

So I wrote him a little snippet - which I post here for your "enjoyment"

Code:
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 :
Code:
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
stefan


Joined: 19 Mar 2004
Posts: 5
Reply with quote
Tthis handy sub did work pretty well Very Happy unfortunatelly it also throws a lot of warnings!
You're right
spandox


Joined: 03 Jul 2004
Posts: 17
Location: Delaware
Reply with quote
My fault -
Code:

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
}
 


Should fix the warnings (stupid programmers, off by one)
Stupid little tip
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum
All times are GMT  
Page 1 of 1  

  
  
 Reply to topic