is there a quick way to exchange the values of two vars without using a third one?
Just a thought but you need to be a little more specific about your definition of quick. If its "quick to type" then yes as the other respondants said you can do
($x,$y)=($y,$x);
If its "quick to execute" then no there is not, as the following benchmark shows
use Benchmark 'cmpthese';
use strict;
my ($x,$y,$u)=(1,2);
sub swapL{
($x,$y)=($y,$x);
}
sub swapTt{
my $t=$x;
$x=$y;
$y=$t;
}
sub swapTu{
$u=$x;
$x=$y;
$y=$u;
}
cmpthese (-10,{list =>\&swapL,
mytmp=>\&swapTt,
glbtmp=>\&swapTu});
__END__
Benchmark: running glbtmp, list, mytmp, each for at least 10 CPU secon
+ds...
glbtmp: 11 wallclocks (10.01 usr + 0.00 sys = 10.01 CPU) @ 106353
+0.80/s (n=10651261)
list: 13 wallclocks (10.19 usr + 0.00 sys = 10.19 CPU) @ 65633
+1.40/s (n= 6686048)
mytmp: 9 wallclocks (10.27 usr + 0.00 sys = 10.27 CPU) @ 90580
+7.23/s (n= 9299017)
Rate list mytmp glbtmp
list 656331/s -- -28% -38%
mytmp 905807/s 38% -- -15%
glbtmp 1063531/s 62% 17% --
A little explaination of this might be useful. When you use the list assignment you are secretly asking perl to create (in this case) two temporary variables (as well as do a bunch of overhead like figuring out how many values it actually has to copy), dynamically, and then to assign those variables to the left side. So while it may look like less code it is in fact much much more. This is nice if you need to swap a couple of variables or reorder a list (check out list slices) in a non-time critical part of your application, but when you need to do the same inside a heavily utilized routine (such as when sorting) then using the less elegant scalar temporary is both faster and has less memory overhead.
And lets not hear about "premature optimization", there are times when you really really will want the the 40%(!) gain. And there are times when you wont... :-) Knowing the difference is the hard part...
Yves / DeMerphq
---
Writing a good benchmark isnt as easy as it might look. |