DEV Community

Discussion on: Swap two numbers without using a temporary variable

Collapse
 
wclayferguson profile image
Clay Ferguson

Not to be negative, but something like this would never be used in production code because the overhead of constructing arrays will be significantly larger than the standard approach of a temp variable.

It's more important that the CPU do less work than to save a line of code. Also, in general 10 lines of simple to read code is always preferable to 1 line of more complex to read code, all other things being equal. Some developers get concerned with counting lines of code, and that's not what matters.

Thread Thread
 
steventhan profile image
Steven Than

I disagree, this code is highly readable. In fact, you'll feel right at home if you come from python world. The following piece of code to swap 2 variables is consider pythonic:

a, b = b, a
Enter fullscreen mode Exit fullscreen mode

If you're worry allocating a temporary array causing performance issue, then you should stay away from JavaScript in the first place

Thread Thread
 
yoursunny profile image
Junxiao Shi

The temporary array is most likely optimized away.

Thread Thread
 
steventhan profile image
Steven Than

That's almost certain, iirc most of the array related code are written C++, at least for Chrome's V8 anyway