-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCallDataArrayOptimization.sol
More file actions
104 lines (78 loc) · 2.28 KB
/
Copy pathCallDataArrayOptimization.sol
File metadata and controls
104 lines (78 loc) · 2.28 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Arrays_NotOptimized {
uint256 public result;
// Params: ["10", "50", "100", "200", "300"]
// transaction cost 47683 gas
// execution cost 25627 gas
function sumOfTheArray(uint256[] calldata array) external {
for (uint256 i = 0; i < array.length; i++) {
result += array[i];
}
}
}
contract Arrays_0 {
uint256 public result;
// Params: ["10", "50", "100", "200", "300"]
// transaction cost 46163 gas
// execution cost 24107 gas
function sumOfTheArray(uint256[] calldata array) external {
for (uint256 i = 0; i < array.length; i++) {
unchecked {
result += array[i];
}
}
}
}
contract Arrays_1 {
uint256 public result;
// Params: ["10", "50", "100", "200", "300"]
// transaction cost 45298 gas
// execution cost 23242 gas
function sumOfTheArray(uint256[] calldata array) external {
uint256 _result;
for (uint256 i = 0; i < array.length; i++) {
unchecked {
_result += array[i];
}
}
result = _result;
}
}
contract Arrays_2 {
uint256 public result;
// Params: ["10", "50", "100", "200", "300"]
// transaction cost 45263 gas
// execution cost 23207 gas
function sumOfTheArray(uint256[] calldata array) external {
uint256 _result;
uint256 _len = array.length;
for (uint256 i = 0; i < _len; i++) {
unchecked {
_result += array[i];
}
}
result = _result;
}
}
contract Arrays_3 {
uint256 public result;
// Params: ["10", "50", "100", "200", "300"]
// transaction cost 45007 gas
// execution cost 22951 gas
function sumOfTheArray(uint256[] calldata array) external {
assembly {
let _end := add(array.offset, shl(5, array.length))
let _result := 0
for { let i := array.offset } 1 {} {
_result := add(_result, calldataload(i))
i := add(i, 0x20)
if eq(i, _end) {
break
}
}
// Store the result
sstore(result.slot, _result)
}
}
}