Cover photo

Tips for saving gas in solidity

For interaction and transacting with smart contracts you need to pay gas fee. Here are some tips for saving gas in Solidity.

Using constant and immutable variables.

For variables, that won’t be ever changed you can use constant or immutable keyword. Constant variables must be fixed at compile-time, immutable variables can be assigned at construction time. Using these keywords not only saves gas (because such variables don’t occupy storage slot), but also improves readability of code.

post image

In Solidity state variables are stored in 256-bit (32-bytes) storage slots, but multiple contiguous variables can be packed in one storage slot if their overall data is less than 32 bytes. Here is example: in first case every variable takes one storage slot, in second case we save 2 storage slot, because variables b, d, f are packed and saved in one storage slot (128 + 64 + 64 = 256).

post image
 Incrementing and Decrementing by one.

There are several ways for making incrementing or decrementing by one. Most effective method - prefix increment/decrement.

post image
 Use unchecked block.

Since Solidity 0.8.0 version compiler automatically performs overflow/underflow checks, that requires additional gas cost. If you are sure, that overflow/underflow is impossible you can use unchecked block to skip checks and save gas.

post image

You can use Solidity compiler optimizer for your code and setting optimizer “runs”. Increasing “runs” decreases calling functions gas cost, but increases cost of deployment smart contract. So test several values of optimizer “runs” for getting better balanced optimization.

post image
Use revert instead of require.

Instead of using require for checking statements, use revert with your custom errors to fail transaction for saving gas.

post image

Thanks for reading. Feel free to dm me if you have any feedback. https://twitter.com/reezo_eth

Also you can mint this article (10 copies) All minters will have a chance to win smth cool from me😉