forked from pynchmeister/LTV-Blockchain-Course
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGasOptimization.sol
More file actions
40 lines (33 loc) · 969 Bytes
/
Copy pathGasOptimization.sol
File metadata and controls
40 lines (33 loc) · 969 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// SPDX-License,Identifier: MIT
pragma solidity ^0.8.30;
contract GasOptimization {
uint256 public total;
// function sumIfEvenAndLessThan99(uint[] memory nums) external {
// for (uint i = 0; i < nums.length; i+=1) {
// bool isEven = nums[i] % 2 == 0;
// bool isLessThan99 = nums[i] < 99;
// if (isEven && isLessThan99) {
// total +=nums[i];
// }
// }
// }
// start -50908 gas
// use calldata - 49163 gas
// load state variables to memory - 48952 gas
// short circuit -
//
function sumIfEvenAndLessThan99(uint[] calldata nums) external {
uint256 _total = total;
uint len = nums.length;
for (uint i = 0; i < len;) {
uint256 num = nums[i];
if (num % 2 ==0 && num <99) {
_total += num;
}
unchecked {
++i;
}
}
total = _total;
}
}