-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy path7.sol
52 lines (43 loc) · 985 Bytes
/
7.sol
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
// SPDX-License-Identifier: MIT
pragma solidity 0.8.19;
// Runtime Gas Optimization
// Use an unchecked block when operands can’t underflow/overflow.
contract test1 {
uint256 k;
function costly(uint j, uint i) external {
if (j > i) {
k = j - i;
}
}
}
contract test2 {
uint256 k;
function efficient(uint j, uint i) external {
if (j > i) {
// the if statement makes sure the below doesn't underflow.
// so we can use unchecked to save gas.
unchecked {
k = j - i;
}
}
}
}
contract test3 {
uint256 k;
function costly() external payable {
for (uint p; p < 10; ++p) {
// some operation
}
}
}
contract test4 {
uint256 k;
function efficient() external payable {
for (uint p; p < 10; ) {
// some operation
unchecked {
++p;
}
}
}
}