0

I have some external functions what receives address lists as calldata to save gas. I know that creating a copy from global variables inside functions can be useful to read less from blockchain variables, however I am not sure if doing the same with read-only calldata types will lead to less gas spending.

Is it make sense to prefer one of the below functions in order to save gas?

function testFunctionA (address[] calldata addressList) external {
    address[] memory path;
    path[0] = addressList[0];
    path[1] = addressList[0];

}

In this case I assume it doesn't make sense until I don't use a1 or a2 more than one time within the same function like in testFunctionC. Is it right? Or is it a better idea to copy list objects from calldata lists into local variables inside the function regardless how many times will I use them?

function testFunctionB (address[] calldata addressList) external {
    address a1 = addressList[0];
    address a2 = addressList[1];
    address[] memory path;
    path[0] = a1;
    path[1] = a2;

}

function testFunctionB (address[] calldata addressList) external {
    address a1 = addressList[0];
    address a2 = addressList[1];
    address[] memory path;
    path[0] = a1;
    path[1] = a2;
    path[2] = a1;
    path[3] = a2;

}

1 Answer 1

0

After reading about the topic the consequences are the following for me:

  • Array reads by index should be avoided when you use the variable more than 1 time. It is cheaper to make a copy and use that inside the function.

  • Create fixed length arrays if it is possible in the given situation. Initializing empty, non-fixed arrays and extend the size by pushing new objects will be more expensive.

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.