Skip to content

Instantly share code, notes, and snippets.

@TomiOhl
Created June 9, 2021 11:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TomiOhl/bd32c25794dae89e4163866fdd7b0ca4 to your computer and use it in GitHub Desktop.
Save TomiOhl/bd32c25794dae89e4163866fdd7b0ca4 to your computer and use it in GitHub Desktop.
Comparing the gas cost of functions with an array parameter in different data locations
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
// Testing the gas cost of two identical functions with array parameters supplied in different data locations
// Costs only apply when called from another contract function
contract ArrayParameterTest {
// Transaction cost 22978 gas (length 1), 28639 gas (length 10), 85249 gas (length 100)
// Execution cost 1130 gas (length 1), 5063 gas (length 10), 44393 gas (length 100)
function addNumbersFromCalldata(uint256[] calldata numbers) external pure returns (uint256) {
uint256 sum;
for (uint256 i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
return sum;
}
// Transaction cost 23628 gas (length 1), 31431 gas (length 10), 109482 gas (length 100); 2%, 10% and 28% increase over calldata
// Execution cost 1780 gas (length 1), 7855 gas (length 10), 68626 gas (length 100); 57.5%, 55% and 55% increase over calldata
function addNumbersFromMemory(uint256[] memory numbers) external pure returns (uint256) {
uint256 sum;
for (uint256 i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
return sum;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment