DEV Community

Cover image for Solidity Quick Tip: Efficiently Swap Two Variables
Oliver Jumpertz
Oliver Jumpertz

Posted on • Edited on • Originally published at oliverjumpertz.com

Solidity Quick Tip: Efficiently Swap Two Variables

Everything you do in Solidity has a cost associated with it: gas. Gas is the unit measuring the computing power the network provides to you when you execute smart contract logic. The more code you write, the more gas the execution costs. There are a few exceptions to it, but they are rare. The network wants to get paid for the computing power it provides to you. So executing smart contract logic costs money. And you, as the creator, are not necessarily the one paying, but your users.

Generally spoken, Solidity is one of the few languages where optimization is a necessity right from the beginning on. This also leads to trivial problems sometimes needing an efficient solution, and this also holds for such a simple thing as swapping two variables.

This is how you could usually swap two variables like in any other language that doesn't offer any syntactic sugar:

uint256 a = 1;
uint256 b = 2;

// swap a and b
uint256 tmp = a;
a = b;
b = tmp;
Enter fullscreen mode Exit fullscreen mode

This code works perfectly fine, but it takes both a lot of code and gas, and there is actually a better way to accomplish the swap with less code and thus less gas consumption.

The Code

Solidity knows Tuples and destructuring assignments. The syntax resembles JavaScript pretty closely, where you can do the same only with square brackets.

If you combine both, like shown below, you actually get one of the most efficient solutions to swap two variables in Solidity.

uint256 a = 1;
uint256 b = 2;

(a, b) = (b, a);
Enter fullscreen mode Exit fullscreen mode

The code you see above is actually a pretty common pattern used by many Solidity developers. It is one of the base patterns you should always keep in the back of your head.

The Whole Tip As An Image

If you like visual content more, or if you want to store it later, I put all this into one image for you. I hope you like it!

A picture showcasing the above code

Before You Leave

If you would love to read even more content like this, feel free to visit me on Twitter or LinkedIn.

I'd love to count you as my ever-growing group of awesome friends!

This post was originally published on my personal blog.

Top comments (1)

Collapse
 
sashrika profile image
Sashrika Waidyarathna

let a = 1;
let b = 3;

[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1

Pretty much similar to javascript. Nice to learn that this is possible with solidity as well. Thanks for sharing..