A Collection of Gas Optimisation Tricks

Also a beginner level one, but it adds up.

If there's a state variable you'll read from more than once in a function, it's best to cast it into memory.
So, instead of:

uint256 bar; 

function foo(uint256 someNum) external {
    someMapping[bar] = someNum;
    someArray[bar] = someNum;
}

you'd be better off with:

uint256 bar; 

function foo(uint256 someNum) external {
    uint256 tempBar = bar; // tempBar is in memory and cheaper to read from
    someMapping[tempBar] = someNum;
    someArray[tempBar] = someNum;
}
6 Likes