1

If I am not modifying the input parameter in the function body are there any reasons a reference type parameter should be labeled as stored in memory?

More generally what are the reasons to go for function foo or bar below. ( the same question goes for other reference types like strings)

function foo(StructA calldata asCallData) external {
    ...
}

function bar(StructA memory asMemory) external {
    ...
}

1 Answer 1

1

Using calldata is cheaper, consumes less gas. However, the disadvantage is that you can't modify the received data, it's read only.

Example based on your code:

//SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

contract BasicContract {
    struct StructA {
        uint varaiable;
    }

    function foo(StructA calldata asCallData) external {
        asCallData.varaiable++; //This will not work
    }
    
    function bar(StructA memory asMemory) external {
        asMemory.varaiable++; //This will work
    }

}

Therefore, if you are just receiving values/data to store it into the contract, using calldata is the preferred method:

Case and point:

//SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

contract BasicContract {

    struct StructA {
       unit varaiable;
    }

    StructA data;

    // Cost: 23817 gas
    function foo(StructA calldata asCallData) external {
        data.varaiable = asCallData.varaiable;
    }

    // Cost: 24182
    function bar(StructA memory asMemory) external {
        data.varaiable = asMemory.varaiable;
    }

}
1
  • 1
    Yes i was aware of that, which is why i phrased it as "If I am not modifying the input parameter in the function body are there any reasons a reference type parameter should be labeled as stored in memory?" . My question is, are there any other considerations
    – FreddyC
    Jan 8 at 21:10

Your Answer

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

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