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

Monday, January 1, 2018

Solidity gas optimization - storage and local variables of basic types


If you have function that does some local computation, try to use access to the global poperties or variables of the contract as rarely as possible. Global variables of a contract represent always storage, so setting the variable relative often result in an enormous gas cost. On the contrary, local variables of basic types are stored in the stack so accessing them does not cost gas. In the following example testMemory has a couple of hundreds of gas cost, but testStorage a couple of hundred thousands. 

contract testContract
{
    int public storageInt = 0;
    
    function testMemory(){
        int j;
        for (int i = 0; i < 100; i ++){
            j++;
        }
    }

    function testStorage(){
        int j;
        for (int i = 0; i < 100; i ++){
            storageInt++;
        }
    }
}