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
Copy file name to clipboardExpand all lines: README.md
+56-3Lines changed: 56 additions & 3 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -3,7 +3,7 @@ A list of common Solidity optimization tips and myths.
3
3
4
4
## Tips
5
5
6
-
### Right Shift Instead of Dividing By 2
6
+
### When dividing by two, use `>> 1` instead of `/ 2`
7
7
8
8
The `SHR` opcode is 3 gas cheaper than `DIV` and also bypasses Solidity's division by 0 prevention overhead.
9
9
@@ -12,10 +12,63 @@ The `SHR` opcode is 3 gas cheaper than `DIV` and also bypasses Solidity's divisi
12
12
13
13
```solidity
14
14
// Unoptimized:
15
-
uint256 two = 4 / 2;
15
+
uint256 foo = bar / 2;
16
16
17
17
// Optimized:
18
-
uint256 two = 4 >> 1;
18
+
uint256 foo = bar >> 1;
19
19
```
20
20
21
+
22
+
### Use `>=` and `<=` instead of `>` and `<`
23
+
24
+
Explanation tbd
25
+
26
+
-[Gas Usage]()
27
+
-[Full Example]()
28
+
29
+
```solidity
30
+
// Unoptimized:
31
+
bool foo = bar > 0;
32
+
33
+
// Optimized:
34
+
bool foo = bar >= 1;
35
+
```
36
+
37
+
38
+
### Using `!=` is usually cheaper than `>` or `<`
39
+
40
+
Explanation tbd
41
+
42
+
-[Gas Usage]()
43
+
-[Full Example]()
44
+
45
+
```solidity
46
+
// Unoptimized:
47
+
uint256 foo = bar < 32;
48
+
49
+
// Optimized:
50
+
uint256 foo = bar != 32;
51
+
```
52
+
53
+
54
+
### Use `<address>.code.length` instead of assembly `extcodesize` to avoid variable overhead
55
+
56
+
Solidity [0.8.1](https://github.com/ethereum/solidity/blob/develop/Changelog.md#081-2021-01-27) implements a shortcut for `<address>.code.length` that avoids copying code to memory. More explanation TBD
0 commit comments