Process
How to Profile and Optimize Gas Consumption
Last updated:
October 28, 2021

Solidity code performance is strictly tied to the gas metering costs as found in the Yellow Paper. As such, gas optimization both borrows from and extends traditional optimization techniques. This guide covers how gas usage of certain functions can be reliably identified and reduced.

Understand gas consumption

Given the existence of a GAS opcode, there is no bulletproof way of estimating the gas consumption of a given function. First, you should study the function and determine inputs that could result in more excessive gas usage. These include:

  • Maximizing any loop iterations or recursion
  • Entering branches that consume the most gas
  • Invoking as many external calls as possible.

With candidate inputs in mind and represented in test cases, the following techniques can be used:

  • Run a gas usage report using a Gas reporting tool (this will measure gas consumption in the test suite)
  • Capture and pin gas consumption in specific tests to prevent regression
  • Use Fuzzing to look for unique inputs that result in extreme gas consumption

Optimizing gas

As for gas optimization, we can recommend this handy guide from Blake West. One thing we will add is that for opcode level gas optimization, you should use an opcode level profiler such as in the Auditless Transaction Debugger.

https://s3.us-west-2.amazonaws.com/secure.notion-static.com/14e40ffa-b005-437f-83ab-a67f6e0c95c9/Untitled.png?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAT73L2G45O3KS52Y5%2F20211019%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Date=20211019T201349Z&X-Amz-Expires=86400&X-Amz-Signature=b9c51d9fa16723022373f02177257444fe22a9353a53e1c769e68a4173c8e0d3&X-Amz-SignedHeaders=host&response-content-disposition=filename%20%3D%22Untitled.png%22
Auditless Debugger, opcode level gas profiler

See Also: