solidity – Reasons Why Compiled Bytecode is Significantly Larger Than Solidity Code

bytecodeoptimizationsolidity

I'm busy optimising my Solidity contract and I noticed some behaviour I don't understand.

When I add the following two getter functions:

function getBaseReward() external view returns (uint256) {
  return _baseReward;
}

function getMaxBonuses() external view returns (uint256) {
  return _maxBonuses;
}

The compiled contract size increases by 0.12kb and the text size of the functions on their own is 0.16kb. They are not very different.

However when I add this function:

function burn(uint256 amount) external {
  onlyOwner();
  _burn(msg.sender, amount);
}

The compiled contract size increases by 0.87kb but the text size of the function is only 0.08kb. That's about 10x more and it's just calling two internal functions. Why is the size increase so out of proportion?

Best Answer

I am assuming that you are extending existing token contracts for the onlyOwner and _burn functionality.

When you do not use the function of the contract that you inherit from, the Solidity compiler will not include the bytecode of these into your contract. Therefore if you only reference your own variable the bytecode for onlyOwner and _burn is not present in the bytecode of your final contract. But as soon as you use/ reference these, the bytecode is added (including all bytecode these functions use). Therefore you need to look what code the functions include that you reference from libraries.

General comment: Comparing string size to bytecode size is not a good comparison, as function names and many other syntactic sugar, does not really increase the size of the bytecode.

Edit:

Some references:

Related Topic