Forums > MaxMSP

any easy way to exchange 2 variables' value in JS

November 13, 2006 | 10:51 am

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


November 13, 2006 | 1:23 pm

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://
http://www.cassiel.com


November 13, 2006 | 1:28 pm

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.


November 13, 2006 | 4:32 pm


November 13, 2006 | 5:19 pm

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.


November 15, 2006 | 12:30 am

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


November 16, 2006 | 3:08 am


Viewing 7 posts - 1 through 7 (of 7 total)