Solidity Storage Variables – Value Assignment in Declaration vs. Constructor

constructordeclarationsoliditystorage

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;
   }
}

Best Answer

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;
   }
} 
Related Topic