In the Solidity by example function Selector example, it mentions that:

Perhaps you can save a tiny amount of gas if you precompute and inline the function selector in your code?

I have a couple questions:

  1. How does precomputing the function selector save gas?

Is it because you avoid calling FunctionSelector.getSelector and since each function call costs gas(txdatanonzero)? The less functions you call the less your gas costs?

  1. Where is this FunctionSelector implemented? Do we need to add it to our Smart contract or is it available automatically?

  2. If it's available automatically, how do we avoid calling getSelector? I'm assuming it's automatically called when you execute a function call on a transaction so how do you avoid it?

contract FunctionSelector {
    function getSelector(string calldata _func) external pure returns (bytes4) {
        return bytes4(keccak256(bytes(_func)));

1 Answer 1


The cited sentence probably has a slightly different meaning. By "precomputing and inlining" they meant to literally precompute the value and inserting it into the smart contract before deploying it:

"transfer(address,uint256)" => 0xa9059cbb

It only applies to cases where you are always calling the same function.

As per the solidity documentation, function selector is the first 4 calldata bytes, then starting from the 5th byte, encoded arguments follow. https://docs.soliditylang.org/en/v0.8.11/abi-spec.html

Not going to provide a functioning solution here, but sure there's a way to encode only the parameters and append them to the precomputed function selector (data is shorter, should be cheaper?).

The getSelector(string calldata _func) is just a concrete implementation how the function selector is calculated on chain.

  • Thanks Stanislav!
    – Tomiwa
    Feb 5, 2023 at 4:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.