is it better to pay extra gas to initialise storage variables that are empty as zeroes in the constructor, or save the gas since the default is zero?

  • Should I pay for something that I already have, or should I not pay for it because I already have it? Hmmmm, tough decision... You know what, I think I'll pay for it. – goodvibration Aug 27 '20 at 13:37

Assigning a variable to the default (0) in the constructor or directly in the contract won't make a difference for execution cost when changing that variable later on. Leaving the variables on the default variable will save you some gas on deployment.

For example, let's say we have the following contract:

contract Foo {
  uint256 public bar;
  function setBar (uint _bar) public {
    bar = _bar;

Deploying this contract costs 106,769 gas (in Remix). Calling setBar with a value of 1 (setting bar to 1) has a cost of 41,684 gas.

If we assign bar directly, e.g.

  uint256 public bar = 0;

deployment costs go up to 107,783 gas. Calling setBar has the same gas cost.

We can also assign bar in the constructor:

  constructor () {
    bar = 0;

This results in a deployment cost of 107,995 gas, and setBar still has the same cost.

  • Hi I'm aware of this hence the question of what is best practice due to the nature of the EVM and fees – NowsyMe Aug 27 '20 at 11:40
  • In static programming languages it's always best to to be as explicit as possible however since there is a cost of being so in solidity, my question remains, what to choose? – NowsyMe Aug 27 '20 at 11:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.