Skip to content

Commit 3afa909

Browse files
committed
✨ Add a few more tips
1 parent 071acc8 commit 3afa909

File tree

1 file changed

+56
-3
lines changed

1 file changed

+56
-3
lines changed

README.md

Lines changed: 56 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ A list of common Solidity optimization tips and myths.
33

44
## Tips
55

6-
### Right Shift Instead of Dividing By 2
6+
### When dividing by two, use `>> 1` instead of `/ 2`
77

88
The `SHR` opcode is 3 gas cheaper than `DIV` and also bypasses Solidity's division by 0 prevention overhead.
99

@@ -12,10 +12,63 @@ The `SHR` opcode is 3 gas cheaper than `DIV` and also bypasses Solidity's divisi
1212

1313
```solidity
1414
// Unoptimized:
15-
uint256 two = 4 / 2;
15+
uint256 foo = bar / 2;
1616
1717
// Optimized:
18-
uint256 two = 4 >> 1;
18+
uint256 foo = bar >> 1;
1919
```
2020

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
57+
58+
- [Gas Usage]()
59+
- [Full Example]()
60+
61+
```solidity
62+
// Unoptimized:
63+
uint256 foo;
64+
assembly {
65+
foo := extcodesize(bar)
66+
}
67+
return foo;
68+
69+
// Optimized:
70+
return bar.code.length;
71+
```
72+
73+
2174
## Myths

0 commit comments

Comments
 (0)