Forge Snapshots Analyzer is a bash script designed to compare and analyze snapshots made with forge snapshot
. Currently, it supports the comparison of two gas snapshots.
It calculates:
- Total gas saved.
- % of gas saved compared to the original unoptimized code.
1️⃣ Ensure the install-forge-snapshot-analyzer.sh
is in the same directory as your snapshots.
2️⃣ Grant execution permissions:
chmod +x install-forge-snapshot-analyzer.sh
3️⃣ Execute the installation script:
./install-forge-snapshot-analyzer.sh
After installation, you'll find a new bash script forge-snapshots-analyzer.sh
in your directory with execution permissions pre-set.
📓 Note: When executing, make the snapshot of the "optimized" code be the first argument and the snapshot from the non-optimized the second argument.
Execute it with:
./forge-snapshots-analyzer.sh snapshot-optimized snapshot-non-optimized
Additionally, you'll notice a new directory named ./forge-snapshot-analyzer-scripts
. This contains all the auxiliary bash scripts that coordinate to analyze your snapshots.
In this repo, there are a few snapshots examples so you can clone the repo and see how the script functions:
- ⭐
.gas-snapshot
: Original snapshot. - ⭐
.gas-snapshot-optimized
: Snapshot with improved gas consumption. - ⭐
.gas-snapshot-bad-opt
: Snapshot where gas consumption did not improve. - ⭐
.gas-snapshot-equal-opt
: Snapshot where individual test consumption changed, but net result was unchanged.
Display examples 🖼️
If code reults in optimization
If code doesn't reult in optimization
If code reults in overall zero improvement
🔧 compare-gas-snapshots.sh
it goes row-by-row in a snapshot, comparing the gas(number)
value with its counterpart in the second snapshot file. When a fuzz test is found, it extracts the value from the μ:Number
. If an invariant test is detected, it defaults the gas consumption to 0 since forge
currently doesn't offer gas metrics for such tests.
The results are saved in a .snapshots-compared-results
file.
🔧 filter-out-zero-gas-results.sh
This script checks the output file from compare-gas-snapshots.sh
. If there's no difference in gas values between snapshots (i.e., the difference is 0), such results get filtered out. The processed file is named .snapshots-compared-filtered
.
🔧 count-total-gas.sh
It counts and displays the total gas consumption for both snapshots. It also shows the total difference in gas. All this derived from the filter-out-zero-gas-results
output file.
🔧 analyze-gas-results.sh
It operates on the file filter-out-zero-gas-results
. It calculates:
- Cumulative sum of the last column (gas saved or not in each test).
- Cumulative sum of the penultimate column (original gas consumption).
- Percentage representation:
(gasSaved / originalConsumption) * 100
.
It then displays the total saved gas and its percentage against the original gas consumption.