ReasonJun

Solidity : Difference between memory and calldata 본문

Blockchain/Solidity

Solidity : Difference between memory and calldata

ReasonJun 2023. 10. 16. 16:36
728x90

Memory and calldata are two different data locations in Solidity. Memory is used to store temporary data during the execution of a function, while calldata is used to store function arguments.

 

Memory

Memory is a temporary data location that is used to store data during the execution of a function. When a function is called, memory is allocated for the function call and all local variables in the function. This memory is cleared when the function returns.

Memory is used for a variety of purposes, including:

  • Storing the results of calculations
  • Storing temporary data that is needed during the execution of a function
  • Passing data between functions

Calldata

Calldata is a temporary data location that is used to store function arguments. It is similar to memory, but it is read-only and cannot be modified.

Calldata is used for a variety of purposes, including:

  • Passing data to functions
  • Returning data from functions
  • Storing data that is needed to execute a function

Differences between memory and calldata

The following table summarizes the key differences between memory and calldata:

Property Memory Calldata
Mutability Mutable Immutable
Scope Temporary (cleared when function returns) Temporary (cleared when function returns)
Usage Storing temporary data, passing data between functions Passing function arguments, returning function data

When to use memory and calldata

In general, it is best to use calldata for function arguments and memory for temporary data. This is because calldata is more efficient, as it does not need to be copied.

However, there are some cases where it is necessary to use memory for function arguments. For example, if the function argument is a struct or an array, then it must be stored in memory.

 

Conclusion

Memory and calldata are two important data locations in Solidity. By understanding how to use them effectively, you can write more efficient and correct Solidity code.

728x90

'Blockchain > Solidity' 카테고리의 다른 글

Solidity : Event  (0) 2023.10.16
Solidity : array example  (0) 2023.10.16
Solidity : mapping  (0) 2023.10.16
Solidity : keccak256  (0) 2023.10.16
Solidity : event / emit  (0) 2023.10.16
Comments