Tuning a contract is not an exact science, but is a balance of security, good coding practices, and cost.
In Ethereum transactions cost gas and hence ether. Reducing the gas consumed by a contract is important in two situations,
- Cost of deploying a contract
- Cost to call the contract functions
OOP principles like Inheritance & Composition facilitate code-reuse and hence automatically reduce byte-size of a contract. However, it is still very much responsibility of the developer to write efficient code to optimize gas usage.
To avoid huge cost in deploying a contract, it is important for developer to write efficient code. Especially when a contract inherits from another or when a contract is composed of another contract(s).
If Contract B
inherits from Contract A
then, during compilation, Solidity compiler injects byte-code of A
into B
. This increases deployment cost for B
. (Essentially size of B
= Size of B
+ Size of A
). Similarly, if Contract C
is composed of Contract D
, byte-code of D
will be compiled into byte-code of C
. But, if you as a developer feel this initial cost is justified as compared to reducing transaction cost
by re-using code, then you have an executive decision to make!
BUT, when you do composition like this:
// Foo bytecode will be loaded into memory from an existing Foo deployment
Foo public foo2 = Foo(0xF00BAA...); //THIS is more efficient compared to new Foo().
In some cases, You can consider alternatives to inheritance. For example, Child contracts that call external functions in a main contract (say, a registry or main storage/logic) will tend to be smaller than Child contracts that inherited a complex contract. This will not only reduce cost of deployment but also cost less gas for transactions
in total.
Another way of reducing the size of by Removing useless code, . for eg:
function p1 ( uint x ){
if ( x > 5)
if ( x*x < 20)
XXX }
In above code line 3 and 4 will never be executed and these type of useless code can be avoided carefully going through the contract logic and that will reduce the size of the smart contract.
Overall, Just choosing Composition vs Inheritance does not make it for gas efficiency. Its pragmatic coding which result in gas efficient code!
For more details, this article helps with good practises for coding gas efficient solidity code.
Hope it helps.