DEV Community

Discussion on: Swap two numbers without using a temporary variable

 
wclayferguson profile image
Clay Ferguson • Edited

It depends on what the variables being swapped hold also, to know performance. If you're swapping two primitives (which are not objects) and you use a temp variable, then there is never any heap memory allocate calls at all, because it's all done on the stack. Any time you do something that causes Objects to get created you're putting a load on the memory allocate, and slowing down the eventual garbage collection etc.

My rule of thumb is never do something the slow way intentionally just because it's slightly more elegant code. As long as the code is clear, the clarity itself is the elegance.

And BTW: I'm not saying a temp variable create calls the allocator. It doesn't. I'm saying creating arrays calls the allocator.

Thread Thread
 
amplanetwork profile image
Ampla Network

Yeah I do agree, It works exactly as you describe in .Net, and other managed languages :-).

Just saying that in JS destructuring is syntactic sugar, I worked 5 years making 2D game frameworks for online lottery games, so can only agree. I think it can be tolerated if it is not done in a heavy statment, like a loop etc. Just my opinion by the way.

Thread Thread
 
wclayferguson profile image
Clay Ferguson

My first 10 years of work was C++, so I know a thing or two about stacks and heaps. haha, and I did agree with everything you were saying.

Thread Thread
 
amplanetwork profile image
Ampla Network

I know we were agree from the begining ha ha, I started coding professionally almost 20 years ago with c++ / c# and JS at the same time (My brain must be a little damaged lol), I hope we master a bit heap, stacks and memory allocation even in managed languages loool.

But it is good to remember how optimization works, and always keep in mind that the way we write code does impact heavily the way it will run.

I remember when I learned in c++ to use a 1 dimensional array as it was a 2 one for performance reason, and then understood that in JS an Array ... is not an Array... but an object with numerical key as properties... No comment... Ha ha ha ha (Until you use a real array like a TypedArray for sure). Definition of fun BTW...

Thread Thread
 
amplanetwork profile image
Ampla Network

Did I really wrote "We were agree", sorry for that, I will return to school to re learn grammar :-)

Thread Thread
 
wclayferguson profile image
Clay Ferguson

We probably have a similar belief on most things, sounds like. I branched off to Java in 1998, and never touched C#. I never forgave Bill Gates for trying to "hijack" Java with his Windows proprietary version of the language, and not until recently and because of VSCode and TypeScript did I personally find forgiveness for MSFT.