Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: swapping vars, two ways, 2 results...

by pg (Canon)
on Dec 18, 2002 at 22:47 UTC ( [id://220971]=note: print w/replies, xml ) Need Help??


in reply to swapping vars, two ways, 2 results...

By doing
my ($b, $a) = ($a, $b)
you are not swaping, you simply defined another set of variables. Try this, it will clearly show you what happend, and why it is way fast:
$a = 100; $b = 200; my ($a, $b) = ($b, $a); print $a, "\n"; #200 print $b, "\n"; #100 print $main::a, "\n";#100 print $main::b, "\n";#200
Update:

When you do:
($b, $a) = ($a, $b)
You are not working against two scalars, in stead you are working against two arrays, and two scalars. Not that it is slow, I don't even think it take less memory as you thought. Although you are not using any temps, Perl is using.

Replies are listed 'Best First'.
Re: Re: swapping vars, two ways, 2 results...
by Sihal (Pilgrim) on Dec 18, 2002 at 23:04 UTC
    well it does use less memory, but that may be due to the length of the vars...
    Anyway, this was a kinda stupid post but I wanted to write it cause I saw in one of my team mates code that he would never swap perls way, but rather Cs way, using a temp var. I first thought why wrinting it Cs way when you can use a more compact form. But then I saw that in some case it was actually totally different both in terms of cpu usage and mem, hence the post.
Re: Re: swapping vars, two ways, 2 results...
by Sihal (Pilgrim) on Dec 18, 2002 at 22:51 UTC
    but why is it that much faster ?

      This ($a,$b) = ($b,$a); is notionally equivalent to

      { local @list; $list[0]=$b; $list[1]=$a; $a=$list[0]; $b=$list[1]; undef @list; }

      Instead of allocating one temprary scalar and doing 3 assignments, it is allocating a temporary list, performing 4 assignments and deallocating the list.


      Examine what is said, not who speaks.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://220971]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (4)
As of 2025-03-19 20:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    When you first encountered Perl, which feature amazed you the most?










    Results (59 votes). Check out past polls.