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.
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!
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)
let a = 1;
let b = 3;
[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1