Solidity Quick Tip: Efficiently Swap Two Variables

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;

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);

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!

Oliver Jumpertz


Feel free to contact me

Contact Me



Join the Newsletter

You will regularly be informed about new content, special offers, and interesting information about software development.

Your data might be transferred to servers located in the USA. By subscribing, you agree to the data transfer. You can revoke your approval at any time by unsubscribing. For more information, please visit the privacy policy.

    We won't send you spam. Unsubscribe at any time.