Doesn't it cost more to pass in variable assignment via a constructor due to changing state?

Wouldn't it be cheaper to just assign them in the code?

I am wondering if there are advantages to using a constructor that I am not considering.

I appreciate any information about the reasons for using a constructor to assign values, as I cannot see why it would be beneficial.

Thanks guys.


I suspect you are talking about the case when the arguments for the constructor are known in advance before deployment. In this case you are right it's more efficient to get rid of the constructor parameters and add them as constants in the code thus potentially eliminating a few state variables and saving on gas.

There are cases, however, when it's not possible to replace state variables with constants in this way, e.g. if a state variable must be mutable i.e. it can be updated later in the lifecycle of the contract. So eliminating the constructor parameters will not be of much benefit in this case.

Another case when constructor parameters are useful is when contract instances are created inside another contract. Let's say there is contract A, that needs to create instances of contract B and these instances should have different names. Name in this case has to be a constructor parameter. You could instead update the bytecode of B with the new name every time before deploying it (this is possible as @flygoing mentioned in the comments) but this will require use of assembly and be potentially error-prone.

Hope my explanations are clear.

  • 2
    Your 3rd paragraph is incorrect. A contract can deploy arbitrary bytcode, see this github.com/yarrumretep/clone-factory/blob/master/contracts/… example where the bytecode is updated to use a library contract on the fly before deploying the bytecode. You could even pass bytecode into a contract function to deploy it. – flygoing Feb 9 '18 at 17:00
  • 1
    Interesting. Thanks for this note. Somehow I was confused by this section in Solidity docs solidity.readthedocs.io/en/develop/…. btw what is the hex"34604457603a80... bytecode in CloneFactory? – medvedev1088 Feb 9 '18 at 17:33
  • 2
    That bytecode is the bytecode that is deployed. It's a simple contract that forwards all calls to it to another address via delegatecalls, i.e. it's a slim, 96 byte contract that has it's own storage but uses the code of another contract. The beefbeefbeefbeef part in the bytecode is the part that gets replaced with the passed in address, which is the address that is delegatecall'ed to. You can read pseudo-source for the bytecode at github.com/yarrumretep/clone-factory/blob/master/… – flygoing Feb 9 '18 at 17:36

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.