Table of contents
Here is a list of tips for reducing gas usage for your solidity smart contract.
There are a lot of points out there and suggested by many masters in this field.
I will try my best to consolidate the majority of them here 👇
**Will update this blog periodically, so save it for further reference
Don't Initialize Variables with Default Value
If the variable is not set/initialized, it is assumed to have a default value (0, false, 0x0, etc., depending on the data type).
If you explicitly initialize it with its default value, you are just wasting gas.
Reading and writing local variables is cheap, whereas reading and writing state variables stored in contract storage are expensive.
Pack your variables!
uint8 is not always cheaper than uint256
Mark immutable variables
Public vs External (External is cheaper)
The public modifier is equivalent to external + internal. In other words, both public and external can be called from outside your contract (like MetaMask), but only the public can be called from other functions inside your contract.
Similarly, if a function is only called by other functions in the contract using the "internal" modifier is good it is cheaper to call
prefix increment is better than postfix increment.
Note to be careful using this optimization whenever the expression's return value is used afterwards, e.g.
uint a = i++ and
uint a = ++i result in different values for
Another benefit of using this method👇
When using any kind of counter (like
_tokenId), starting it off at
1 instead of
0 will make the first mint slightly cheaper. In general, writing a value to a slot that doesn’t have one will be more expensive than writing to one that does, so keep that in mind.
Delete variables that you don’t need.
In Ethereum, you get a gas refund for freeing up storage space. If you don’t need a variable anymore, you should delete it using the delete keyword provided by solidity or by setting it to its default value.
Did you find this article valuable?
Support 0xViking by becoming a sponsor. Any amount is appreciated!