In my attempt to use my twitter and linkedIn to share interesting things and insights in Web3 on Ethereum, EVM, smart contracts, which I come across in my daily work as a web3 dev.
Here we go:
Announcing – “Solidity Tips and Tricks Series”.
Solidity Tips and Tricks #1: Unchecked Arithmetic trick
Before solidity compiler version 0.8.0, Solidity didn’t revert to variable overflow. Hence, we have been using OpenZeppeline’s safemath library to handle overflows and underflows.
However, starting from the Solidity version 0.8, this flaw was fixed. As such, Solidity was able to revert on overflows, which also eliminated the need for SafeMath. BUT, this made the arithmetic operations more expensive in terms of gas. This is the “checked arithmetic” for you and the default behavior of the uint / int data types in Soliditiy version 0.8 onwards.
Now, consider a standard for loop which uses i++
or i–-
for traversing indices. Thing to be noted here is: Since every operation in smart contract is going to cost you gas, the number of for loops are usually finite, lower in value to ensure we don’t hit the block gas limit.
Since, we know that “i” is going to be finite, and certainly less than max uint256 value, we can circumvent checked arithmetic and save the gas costs.
Here is the helper function that will help us to use the unchecked arithmetic trick:
function unsafeInc (uint x) private pure returns (uint) { unchecked { return x + 1; } }
And then in the for loop:
for (uint i =0; i < array.length; i = unsafeInc(i)) { // OPERATIONS }
When it comes to optimising for loops, it goes long way irrespective of language and framework. Solidity requires extra attention to these details because you are paying gas ( real money ) for each compute on chain. There are few more for loop optimisations that can be done. More on that in the future posts of the series. Do follow me on either of my twitter or linkedIn.
Leave a Reply