You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
gas is the cost for on-chain computation and storage. examples:
addition costs 3 gas, keccak-256 costs 30 gas + 6 gas for each 256 bits of data being hashed.
sending a transaction costs 21,000 gas (intrinsic gas).
creating a contract costs 32000 gas.
each calldata byte costs gas (gas per byte equal to 0, and 16 gas for the others), the larger the size of the transaction data, the higher the gas fees.
constant values can sometimes be cheaper than immutable values:
- for a constant variable, the expression assigned to it is copied to all the places where it is accessed and also re-evaluated each time, allowing local optimizations.
- immutable variables are evaluated once at construction time and their value is copied to all the places in the code where they are accessed. For these values, 32 bytes are reserved, even if they would fit in fewer bytes.
mappings are cheaper than arrays
avoid dynamically sized arrays
an array is not stored sequentially in memory but as a mapping.
you can pack Arrays but not Mappings.
it’s cheaper to use arrays if you are using smaller elements like uint8 which can be packed together.
you can’t get the length of a mapping or parse through all its elements, so depending on your use case, you might be forced to use an Array even though it might cost you more gas.
use bytes32 rather than string/bytes
if you can fit your data in 32 bytes, then you should use bytes32 datatype rather than bytes or strings as it is much cheaper in solidity.
any fixed size variable in solidity is cheaper than variable size.
modifiers
for all the public functions, the input parameters are copied to memory automatically, and it costs gas.
if your function is only called externally, then you should explicitly mark it as external.
external function’s parameters are not copied into memory but are read from calldata directly.
internal and private are both cheaper than public and external when called from inside the contract in some cases.
no need to initialize variables with default values
if a variable is not set/initialized, it is assumed to have the default value (0, false, 0x0 etc depending on the data type). If you explicitly initialize it with its default value, you are just wasting gas.