0

What difference does it make if I assign the value of a storage variable in the same line where it is declared vs if I assign its value in the constructor? Which would be the preferred approach? And if both would have the same exact effect, which would be the most gas-efficient implementation?

Example:

contract Demo {
   uint256 public a = 10_000_000;
   constructor() {}
}

vs

contract Demo {
   uint256 public a;
   constructor() {
      a = 10_000_000;
   }
}

2 Answers 2

1

In your particular example, the difference is negligible. There are 137 opcodes used for the first case and 140 for the second case. In the first case, the storage is initialized practically immediately:

enter image description here

while in the second case there is some boilerplate code to get to the initialization:

enter image description here

(solidity 0.8.0 and a=10 instead of 10000000)

However, constructors are used to customize contract for the initial values from deployment scripts. Or when contracts are created by other contracts.

For example, you want your contract to have not hardcoded name but initialized from deployment script, so you use constructor:

contract MyContract {
   string private _name;
   constructor(string memory name) {
      _name = name;
   }
   function getName() public view returns(string memory) {
     return _name;
   }
} 
3
  • Thanks for this. What's that awesome tool you used above to get the opcodes? Dec 26, 2021 at 0:32
  • 1
    Its remix debugger: remix.ethereum.org
    – rlib
    Dec 26, 2021 at 0:48
  • I use Remix all the time, but haven't used its debugger tool as much. Thanks. Dec 26, 2021 at 10:39
0

In the case of the examples you posted, there is no difference. When you initialize the state variable in the line of declaration, it's the same as you if you do it in the constructor.

If you want to have state variables initialized at contract creation, there is no way to optimize this. It should use a similar amount of gas in either implementation.

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.