in reply to Re: swapping vars, two ways, 2 results...
in thread swapping vars, two ways, 2 results...

"perl's way" is better(?), faster, cheaper, shorter(just), and preferable in every way(opinion?).

c:\test>perl -MBenchmark=cmpthese my ($a,$b)=('a'x1000,'b'x1000); cmpthese( -10, { PERL=> sub{ ($a, $b) = ($b, $a); }, C => sub{ my $t=$a, $a=$b, $b=$t; }, XOR => sub{ $a^=$b^=$a^=$b; }, } ); ^Z Benchmark: running C, PERL, XOR, each for at least 10 CPU seconds... C: 10 wallclock secs (10.01 usr + 0.00 sys = 10.01 CPU) @ 19 +7752.07/s (n=1980487) PERL: 10 wallclock secs (10.30 usr + 0.00 sys = 10.30 CPU) @ 12 +1439.73/s (n=1250222) XOR: 10 wallclock secs (10.03 usr + -0.01 sys = 10.02 CPU) @ 33 +5113.02/s (n=3356492) Rate PERL C XOR PERL 121440/s -- -39% -64% C 197752/s 63% -- -41% XOR 335113/s 176% 69% -- c:\test>

If performance isn't a concern I use list assignment, if it is, I'd use the XOR method.


Examine what is said, not who speaks.

Replies are listed 'Best First'.
Re: Re: Re: swapping vars, two ways, 2 results...
by jdporter (Paladin) on Dec 19, 2002 at 03:35 UTC
    If performance isn't a concern I use list assignment, if it is, I'd use the XOR method.
    Besides being obfuscatory, the XOR method only works on numbers or strings. It doesn't work on other things, like references and filehandles. The perlish method works on anything.

    jdporter
    ...porque es dificil estar guapo y blanco.

      Good point on the non-scalars though the OP was talking about ... 2 big vars my $a = "10"x10000; ....

      If I was dealing with non-scalars and performance was critical, I'd use the temp var.

      ... Besides being obfuscatory, the XOR method ...

      Do you really find it confusing?


      Examine what is said, not who speaks.

Re: Re: Re: swapping vars, two ways, 2 results...
by RMGir (Prior) on Dec 19, 2002 at 19:24 UTC
    XOR swapping of strings in perl is BAD. I think it's merlyn who refers to these things as bad memes?

    The reason is that if the strings are different lengths, you get subtly "broken" results...

    my ($a,$b)=("a","bb"); printf("/%s/ (%d bytes) /%s/ (%d bytes)\n",$a,length($a),$b,length($b) +); $a^=$b^=$a^=$b; printf("/%s/ (%d bytes) /%s/ (%d bytes)\n",$a,length($a),$b,length($b) +);'
    This results in:
    /a/ (1 bytes) /bb/ (2 bytes) /bb/ (2 bytes) /a/ (2 bytes)
    The unexpected "2 bytes" for /a/ occurs because the string is still 2 characters long, but the 2nd character is now null.

    This can (and will) trip you up later, because $b ne "a", even though they print the same.
    --
    Mike

      Your right of course. Its not good at all with different length strings.


      Examine what is said, not who speaks.

Re: Re: Re: swapping vars, two ways, 2 results...
by Sihal (Pilgrim) on Dec 19, 2002 at 08:41 UTC
    By the way, if the two vars are very differents sizes, Perl's way gets slower.