...by Daniel Szego
quote
"On a long enough timeline we will all become Satoshi Nakamoto.."
Daniel Szego

Monday, January 1, 2018

Solidity gas optimization - creating child contract versus child struct


Solidity provides the way to create a new contract from an existing one with the help of the new keyword. It is important to note however that contract creation is one of the most expensive operation in solidity. If the use-case allows however you can simply use a struct instead if subcontracts. Certainly it must be payed attention how the functions are realized that should be associated with the child contract. In the bellow example creating the contracts with ContractFactory requires at least 4 times as much gas as creating almost the same functionality with StructFactory.    

contract SubContract{
    int subVariable;
    
    function SubContract(int _initValue){
        subVariable = _initValue;
    }
}

contract ContractFactory{
    SubContract [] subContract;
    
    function generate(){
        for (int i = 0; i < 10; i++) {
        SubContract newContract = new SubContract(i);  
        subContract.push(newContract);
        }
    }
}

contract StructFactory{
    
    struct SubStruct {
        int subVariable;
    }
    
    SubStruct [] subStruct;
    
    function generate(){
        for (int i = 0; i < 10; i++) {
        SubStruct memory newStruct = SubStruct(i);  
        subStruct.push(newStruct);
        }
    }
}