Frontend Development 4 min read

Analyzing Space Usage and Performance of JavaScript Destructuring Assignment for Value Swapping

This article examines whether JavaScript destructuring assignment saves memory or runs faster than the traditional temporary‑variable swap by analyzing the creation of a temporary array, benchmarking loop performance, and discussing observed inconsistencies that may stem from JIT optimizations.

ByteFE
ByteFE
ByteFE
Analyzing Space Usage and Performance of JavaScript Destructuring Assignment for Value Swapping

Compared with the traditional method that requires an extra temporary variable for swapping values, using destructuring assignment is convenient, but raises questions about space consumption and execution speed.

Traditional swap:

let c = b;

b = a;

a = c;

Destructuring swap:

[a, b] = [b, a];

Analyzing the process shows that destructuring first evaluates the right‑hand array from left to right, creates a temporary array containing two elements, and then assigns the values to the left‑hand variables, which does not save space and actually uses an extra array slot.

Performance tests with billions of iterations reveal that the destructuring swap is slower. Sample benchmark code:

const times = 3000000000;
let a = 1, b = 2;
let time1 = new Date().getTime();
while (i++ < times) {
  [a, b] = [b, a];
  let c = b;
  b = a;
  a = c;
  let d = b;
  b = a;
  a = d;
}
console.log(new Date().getTime() - time1); // ~4300 ms

time1 = new Date().getTime();
while (i-- >= 0) {
  [a, b] = [b, a];
  [a, b] = [b, a];
  let c = b;
  b = a;
  a = c;
}
console.log(new Date().getTime() - time1); // ~6400 ms

The slower speed is likely due to the overhead of creating the temporary array and checking for undefined elements during each assignment.

An additional curious observation shows that on a MacBook Pro the loop with extra operations runs noticeably faster than the simpler loop, while on a Windows PC the timings are almost identical, suggesting that JIT compilation differences may affect the results.

PerformanceDestructuringspace efficiencyvalue swapping
ByteFE
Written by

ByteFE

Cutting‑edge tech, article sharing, and practical insights from the ByteDance frontend team.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.