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

I was going to point out the same thing, and that doing it the Perl way is actually faster, but it turns out ikegami's XOR trick is slightly faster:
use Benchmark; sub xor_swap { my($num1x,$num2x) = @_; $num1x ^= $num2x; $num2x ^= $num1x; $num1x ^= $num2x; } sub perl_swap { my($num1x,$num2x) = @_; ($num1x,$num2x)=($num2x,$num1x); } timethese (1_000_000, { xor_swap => sub { xor_swap(38,970); }, perl_swap => sub { perl_swap(38,970); } });

Results:

Benchmark: timing 1000000 iterations of perl_swap, xor_swap... perl_swap: 5 wallclock secs ( 4.87 usr + 0.00 sys = 4.87 CPU) @ 205338.81/s (n=1000000) xor_swap: 4 wallclock secs ( 4.23 usr + 0.00 sys = 4.23 CPU) @ 236406.62/s (n=1000000)

Replies are listed 'Best First'.
Re^4: Extraction of List of Coordinates
by Roy Johnson (Monsignor) on Oct 06, 2004 at 15:31 UTC
    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...


    Caution: Contents may have been coded under pressure.