any easy way to exchange 2 variables' value in JS
hi all,
is there any easy way to exchange 2 variables' value in JavaScript?
something like this in python.
a,b = b,a
hanshin
Telefonate ohne weitere Kosten vom PC zum PC: http://messenger.yahoo.de
On 13 Nov 2006, at 10:51, Kim Han Shin wrote:
> is there any easy way to exchange 2 variables' value in JavaScript?
Leaving aside the obvious temp variable approach, when I was young
and computers had not very much memory at all, this one had a certain
cachet:
a = a ^ b
b = a ^ b
a = a ^ b
nick rothwell -- composition, systems, performance -- http://
www.cassiel.com
Well sorry if i'm stating the obvious but using a 3rd variable would work. If you do not want to use a third one,
a = a + b
b = a - b
a = a - b
would work in three steps.
Hmm, I have no idea about the speed comparisons between programming languages, but as far as I know, ability to call for swapping two variables in a single line does not necessarily mean that it is going to be interperetad and executed faster. It's just the way you tell things to compiler/interpreter, and does not give clues about speed I think. Single line of swapping code could take longer or shorter to execute. Speed is not releated to that.
It takes longer to write that code anyways. If that is the issue.
On 13-Nov-2006, at 17:32, Kim Han Shin wrote:
> i know it works but using tuple type in python is more simple and
> elegant: just one step.
Over and above Batuhan's very correct point, it is worth mentioning
that Python, JS, and even message-passing in plain-vanilla Max have
far, far more overhead than any of the code snippets listed in this
thread.
Nick's catchy code disassembles on PPC to
xor r30,r30,r29
xor r29,r30,r29
xor r30,r30,r29
and the more standard swap-with-temp-var disassembles to
mr r28,r30
mr r30,r29
mr r29,r28
Either way it's very few cycles, your Python code will not be faster
than that. Sending a message through a patch cord is many times the
number of cycles.
If it's typing and transparency you're concerned about, write a Swap
method/function.
-------------- http://www.bek.no/~pcastine/Litter/ -------------
Peter Castine +--> Litter Power & Litter Bundle for Jitter
Universal Binaries on the way
iCE: Sequencing, Recording &
Interface Building for |home | chez nous|
Max/MSP Extremely cool |bei uns | i nostri|
http://www.dspaudio.com/ http://www.castine.de