No built-in swap function?

Robert Brewer fumanchu at amor.org
Wed Apr 21 03:10:29 EDT 2004


Simon Wittber wrote:
> import time
> def tupleSwap(a,b):a,b = b,a
> def tempSwap(a,b):
>     t = a
>     a = b
>     b = t
> def xorSwap(a,b):
>     a ^= b
>     b ^= a
>     a ^= b
> 1 million tuple swaps in 1.78324228359 seconds.
> 1 million temp swaps in 1.53032270861 seconds.
> 1 million xor swaps in 2.17933312753 seconds.
> 
> Interestingly, using psyco.full() produced these results:
> 1 million tuple swaps in 3.06005958858 seconds.
> 1 million temp swaps in 3.01621882111 seconds.
> 1 million xor swaps in 3.03376686143 seconds.
> 
> The xorswap function is not much use for anything other than numbers,
> however, I would have expected a psyco'ed xorSwap to much faster than
> the alternatives!

Well, the xorswap does the same work as the tempswap, plus the xoring:

>>> def ts(a, b):
... 	t = a
... 	a = b
... 	b = t
... 	
>>> dis.dis(ts)
  2           0 LOAD_FAST                0 (a)
              3 STORE_FAST               2 (t)

  3           6 LOAD_FAST                1 (b)
              9 STORE_FAST               0 (a)

  4          12 LOAD_FAST                2 (t)
             15 STORE_FAST               1 (b)
             18 LOAD_CONST               0 (None)
             21 RETURN_VALUE        


That's 3 LOAD_FAST, and 3 STORE_FAST operations.

>>> def xs(a, b):
... 	a ^= b
... 	b ^= a
... 	a ^= b
... 	
>>> dis.dis(xs)
  2           0 LOAD_FAST                0 (a)
              3 LOAD_FAST                1 (b)
              6 INPLACE_XOR         
              7 STORE_FAST               0 (a)

  3          10 LOAD_FAST                1 (b)
             13 LOAD_FAST                0 (a)
             16 INPLACE_XOR         
             17 STORE_FAST               1 (b)

  4          20 LOAD_FAST                0 (a)
             23 LOAD_FAST                1 (b)
             26 INPLACE_XOR         
             27 STORE_FAST               0 (a)
             30 LOAD_CONST               0 (None)
             33 RETURN_VALUE        

That's 6 LOAD_FAST, and 3 STORE_FAST operations, plus XOR'ing.


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org




More information about the Python-list mailing list