Using bool for storage incurs overhead
Discover how using `bool` for storage can lead to unnecessary overhead. Learn how replacing `bool` with uint256(1) and uint256(2) can help you avoid expensive operations and optimize gas usage. Find out more in this informative blog post.
Category
gas
Languages
solidity
Analysis Layer
static
Severity
info
Use uint256(1) and uint256(2) for true/ false to avoid a Gwarmaccess (100 gas), and to avoid Gsset (20000 gas) when changing from false to true, after having been true in the past. See source.
pragma solidity ^0.8.0;
contract BoolStorage {
bool private flag;
function setFlag(bool _flag) external {
flag = _flag;
}
function getFlag() external view returns (bool) {
return flag;
}
}
Using bool data type for storage in Solidity can incur unnecessary gas costs, especially when changing states from false to true after having been true in the past.
To mitigate these gas costs, you can utilize uint256 values uint256(1) and uint256(2) to represent true and false respectively.
The following example demonstrates how to update a flag using uint256 values instead of bool:
pragma solidity ^0.8.0;
contract UintStorage {
uint256 private flag;
function setFlag(uint256 _flag) external {
require(_flag == 1 || _flag == 2, "Invalid flag value");
flag = _flag;
}
function getFlag() external view returns (bool) {
return flag == 1;
}
}
By utilizing uint256 values 1 and 2 as representations for true and false respectively, you can avoid the Gwarmaccess and Gsset gas costs when changing the flag state.
Remember to include appropriate validation when setting the flag value to ensure only 1 or 2 can be used to maintain the logical integrity of the flag.
Using uint256 instead of bool for storage in such scenarios can enhance gas efficiency in your Solidity contracts.