Created
June 9, 2021 11:39
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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