1

I am experimenting with some gas savings and I found out that inside a function declaring a variable first and then assigning a value is more gas efficient than making the declaration and assignment in one line. My question is that why does this happen? I would think that the shorter version produces less code and less code costs less in this scenario.

checkVariableDeclaration1 >> 23466 gas
checkVariableDeclaration2 >> 23412 gas
---------------------------------------
difference >> 44 gas



function checkVariableDeclaration1(uint[] calldata nums) public pure returns (uint) {
    uint n1 = nums[0];
    uint n2 = nums[1];
    uint n3 = nums[2];
    uint n4 = nums[3];
    return n1 + n2 + n3 + n4;

}

function checkVariableDeclaration2(uint[] calldata nums) public pure returns (uint) {
    uint n1;
    uint n2;
    uint n3;
    uint n4;
    n1 = nums[0];
    n2 = nums[1];
    n3 = nums[2];
    n4 = nums[3];
    return n1 + n2 + n3 + n4;

}

1 Answer 1

2

In the second example, you assign zero to n1 - n4 before assigning the final value. This can be seen if you compile the contract using intermediate representation

solc Check.sol -ir

produces:

/// @src 0:477:484 "uint n1"
let var_n1_51
let null_t_uint256_11 := null_value_for_split_t_uint256()
var_n1_51 := null_t_uint256_11
/// @src 0:494:501 "uint n2"
let var_n2_54
let null_t_uint256_12 := null_value_for_split_t_uint256()
var_n2_54 := null_t_uint256_12
/// @src 0:511:518 "uint n3"
let var_n3_57
let null_t_uint256_13 := null_value_for_split_t_uint256()
var_n3_57 := null_t_uint256_13
/// @src 0:528:535 "uint n4"
let var_n4_60
let null_t_uint256_14 := null_value_for_split_t_uint256()
var_n4_60 := null_t_uint256_14

4
  • 1
    Any insight on why assigning default values first makes it cheaper?
    – Ryan Sea
    Aug 22, 2022 at 1:36
  • That is a good question. Can you share your compiler settings (version, number of optimization runs, etc..)? Aug 22, 2022 at 13:47
  • This was a simple test using the default settings of Remix. After doubling the number of variables the difference increased even more. With 8 variables the difference was around 120 gas. Do you think this would work on the mainnet as well or there is a chance that its produced by a Remix compiler setting?
    – rihekopo
    Aug 24, 2022 at 12:12
  • Yes, I'm pretty sure this doesn't just happen in the Remix VM (remix-ide.readthedocs.io/en/latest/run.html#environment). As a test you could try deploying to a public test network. The compiler setting can be found under Advanced Configuration. Aug 24, 2022 at 13:18

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.