Chose your function names carefully in Solidity to save execution gas
Your functions are converted into function selectors, which are the first four bytes of a keccak256 hash of the function name.
When your smart contract is called, Solidity compiles code that checks in order if you are calling each function selector until it finds it.
If you have a very commonly used function, make sure its selector has a low value, so it is likely to be the first comparison made.
The savings are quite minimal (44 gas when 2 functions) and for most smart contracts it isn't a consideration, but it's a really neat trick to get every last bit of gas saving.
pragma solidity >=0.8.4;
contract FunctionSelectorExample {
/*
This is the mapping of selectors (in order) to the function names
{
"706f4c9e": "funcA()", // first - so will be cheapest as itll be the first comparison
"7092150a": "funcC()"
"84c5a5ef": "funcB()", // last - so a bit more expensive as it will be the third comparison
} */
// costs 24,364 gas
// (cheapest as selector is 706f4c9e, which is first in order)
function funcA() public {
}
// costs 24,415 gas
// (most expensive, as selector is 84c5a5ef, which is third in order)
function funcB() public {
}
// costs 24,390 gas
function funcC() public {
}
}
Top comments (0)