You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The EVM works with 256bit/32byte words. For smaller data types, further operations are performed to downscale from 256 bits to the required lower bites type, and therefore having uint8 as an iterator consumes more gas than keeping it to uint256.
pragma solidity^0.6.12;
/** * Show the difference in gas costs between a loop that uses a uint8 variable * and one that uses uint256 variable. * * Both contracts compiled with `Enable Optimization` set to 200 runs. */contractLoopUint8 {
address[] internal arr;
// 1st call; arr.length == 0: gas cost 42719// 2nd call; arr.length == 1: gas cost 30322// 3rd call; arr.length == 2: gas cost 32925function add(address_new) public {
for (uint8 i =0; i < arr.length; i++) {
if (arr[i] == _new) {
require(false, 'exists');
}
}
arr.push(_new);
}
}
contractLoopUint256 {
address[] internal arr;
// 1st call; arr.length == 0: gas cost 42713// 2nd call; arr.length == 1: gas cost 30304// 3rd call; arr.length == 2: gas cost 32895function add(address_new) public {
for (uint256 i =0; i < arr.length; i++) {
if (arr[i] == _new) {
require(false, 'exists');
}
}
arr.push(_new);
}
}
Recommendation
Use uint256 for the loop iterators.
The text was updated successfully, but these errors were encountered:
Description
The EVM works with 256bit/32byte words. For smaller data types, further operations are performed to downscale from 256 bits to the required lower bites type, and therefore having
uint8
as an iterator consumes more gas than keeping it touint256
.Recommendation
Use
uint256
for the loop iterators.The text was updated successfully, but these errors were encountered: