in reply to Re^3: Extraction of List of Coordinates
in thread Extraction of List of Coordinates

After compensating for everything I could think of, XOR still won. Surprisingly, it won against the standard temp-variable swap. Incredibly, it won against a sub that simply returned the numbers in reverse order (in fact, temp swapping generally beat that, too!). I could only think that it wins because the integer math makes things simpler internally.

I tried different types of arguments, and preprocessing the argument list to force it to integer. Speedup was slight, if there was any at all, for the integer-forced versions. Perl swapping lost pretty consistently in all cases. Temp swapping and return-value swapping beat XOR for swapping strings, sometimes. I got inconsistent results.

Benchmark code follows...

use Benchmark 'cmpthese'; my @swapthese; sub xor_swap { my ($x,$y)=@swapthese; $x ^= $y; $y ^= $x; $x ^= $y; ($x,$y); } sub perl_swap { my ($x,$y)=@swapthese; ($x,$y) = ($y,$x); ($x,$y); } sub perl_i_swap { my ($x,$y)=@swapthese; ($x,$y) = ($y^0,$x^0); ($x,$y); } { my $tmp; sub tmp_swap { my ($x,$y)=@swapthese; $tmp=$x; $x=$y; $y=$tmp; ($x,$y); } sub tmp_i_swap { my ($x,$y)=@swapthese; $tmp=$x^0; $x=$y^0; $y=$tmp; ($x,$y); } } sub ret_swap { my ($x,$y)=@swapthese; ($y,$x); } sub ret_i_swap { my ($x,$y)=@swapthese; $x ^= 0; $y ^= 0; ($y,$x); } for my $S ([38,970], [38.1,970], ['foo',38], ['foo','barbell']) { @swapthese = @$S; print "Swapping @swapthese\n"; print "XOR: @{[xor_swap()]}\n"; print "Perl: @{[perl_swap()]}\n"; print "Perl I: @{[perl_i_swap()]}\n"; print "TMP: @{[tmp_swap()]}\n"; print "TMP I: @{[tmp_i_swap()]}\n"; print "RET: @{[ret_swap()]}\n"; print "RET I: @{[ret_i_swap()]}\n"; cmpthese (-2, { xor_swap => \&xor_swap, perl_swap => \&perl_swap, tmp_swap => \&tmp_swap, ret_swap => \&tmp_swap, perl_i_swap => \&perl_swap, tmp_i_swap => \&tmp_swap, ret_i_swap => \&tmp_swap, }); }

Caution: Contents may have been coded under pressure.