DEV Community

CoinMonks
CoinMonks

Posted on • Originally published at Medium on

Minimize Gas in Your Smart Contracts

Photo by Jess Bailey on Unsplash

Simple Hacks to reduce the Gas you pay for Smart Contracts

I went from paying excessive amounts in gas to paying a reasonable amount after doing a course on solidity development.

I’ll tell you the main tricks here so you don’t waste your time doing the entire course.

1. Smaller uints

If you’ve got multiple uints inside a struct use a small-sized uint. This allows Solidity to use less storage.

Convert this:


struct NormalStruct {
 uint a;
 uint b;
 uint c;
}
Enter fullscreen mode Exit fullscreen mode

To this:

struct MiniMe {
 uint32 a;
 uint32 b;
 uint c;
}
Enter fullscreen mode Exit fullscreen mode

MiniMe will cost less gas than NormalStruct because of struct packing

2. View Functions Don’t Cost You a Thing

View functions don’t cost any gas when they’re called externally by a user.

This is because view functions don’t actually change anything on the blockchain — they only read the data.

Wherever possible use a view function. Here’s an example:

# [https://github.com/spiyer99/CryptoZombies/blob/master/contracts/zombie\_helper.sol#L36](https://github.com/spiyer99/CryptoZombies/blob/master/contracts/zombie_helper.sol#L36)

function getZombiesByOwner(address _owner) external view returns(uint[] memory) {
  uint[] memory result = new uint[](ownerZombieCount[_owner]);
  uint counter = 0;
  for (uint i = 0; i < zombies.length; i++) {
    if (zombieToOwner[i] == _owner) {
      result[counter] = i;
      counter++;
    }
  }
  return result;
}
Enter fullscreen mode Exit fullscreen mode

This function allows us to find all the zombies that someone owns.

We do this by iterating through every single zombie.

Yes this is naive. We could simply create a hash map. That would reduce the lookup to O(1).

But it’s also cheaper than a hash map. So it’s better. The end.

Conclusion

And that’s it! These two things saved me a considerable amount of gas. I hope they help you too.


Top comments (0)