0xViking
0xViking

0xViking

Solidity Devs do something! Save some gas

Solidity Devs do something! Save some gas

Tips to save gas usage in your solidity smart contract

0xViking's photo
0xViking
·May 26, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

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.

image.png

Reading and writing local variables is cheap, whereas reading and writing state variables stored in contract storage are expensive.

image.png

Pack your variables!

image.png

uint8 is not always cheaper than uint256

image.png

Mark immutable variables

image.png

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.

image.png

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 a.

image.png

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!

Learn more about Hashnode Sponsors
 
Share this