Gas Optimization Tips Don't Always Work

Certain gas-saving techniques might not work in every situation. Take, for example, you might think flipping the condition in an if-else statement like this:

if (!cond) {
    // False branch
} else {
    // True branch
}

to this:

if (cond) {
    // True branch
} else {
    // False branch
}

would save gas because it skips flipping the condition. But it’s not always that straightforward. Surprisingly, doing this can sometimes end up costing you more, thanks to how the Solidity compiler works. It’s a bit of a wildcard.

The takeaway? Don’t just assume an optimization will work better without testing it out first. Some of these tips are here to make you aware of where the compiler might throw you a curveball.

We’ve tagged the tricks that aren’t one-size-fits-all in this guide. Since gas optimization often depends on the specific things the compiler is up to at the moment, it’s smart to compare both the “optimized” and the regular versions to see if you’re truly saving gas. We’ve also noted some instances where, against all odds, an optimization ends up being more costly.

Also, keep in mind that some optimization results might shift if you’re compiling with the --via-ir option in Solidity. It’s all about staying flexible and testing thoroughly1.

results matching ""

    No results matching ""